Convert String containing several numbers into integers(将包含多个数字的字符串转换为整数)
问题描述
我知道这个问题过去可能已经被问过好几次了,但无论如何我都会继续.
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>
这篇关于将包含多个数字的字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将包含多个数字的字符串转换为整数


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01