将包含多个数字的字符串转换为整数

2022-01-14 00:00:00 string integer c++

我知道这个问题过去可能已经被问过好几次了,但无论如何我都会继续.

I realize that this question may have been asked several times in the past, but I am going to continue regardless.

我有一个程序要从键盘输入中获取一串数字.数字将始终采用66 33 9"的形式本质上,每个数字都以空格分隔,用户输入的数字将始终包含不同数量的数字.

I have a program that is going to get a string of numbers from keyboard input. The numbers will always be in the form "66 33 9" Essentially, every number is separated with a space, and the user input will always contain a different amount of numbers.

我知道,如果每个用户输入的字符串中的数字数量是恒定的,则使用sscanf"会起作用,但对我来说并非如此.另外,因为我是 C++ 新手,所以我更喜欢处理字符串"变量而不是字符数组.

I'm aware that using 'sscanf' would work if the amount of numbers in every user-entered string was constant, but this is not the case for me. Also, because I'm new to C++, I'd prefer dealing with 'string' variables rather than arrays of chars.

推荐答案

我假设您想读取整行,并将其解析为输入.所以,首先抓住这条线:

I assume you want to read an entire line, and parse that as input. So, first grab the line:

std::string input;
std::getline(std::cin, input);

现在把它放在 stringstream 中:

std::stringstream stream(input);

并解析

while(1) {
   int n;
   stream >> n;
   if(!stream)
      break;
   std::cout << "Found integer: " << n << "
";
}

记得加入

#include <string>
#include <sstream>

相关文章