将包含多个数字的String转换为整数 [英] Convert String containing several numbers into integers

查看:148
本文介绍了将包含多个数字的String转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这个问题在过去可能已被问过好几次了,但我会继续这样做。

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 << "\n";
}

请记住包含

#include <string>
#include <sstream>

这篇关于将包含多个数字的String转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆