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>
这篇关于将包含多个数字的字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将包含多个数字的字符串转换为整数
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
