想要使用 sstream 解析 int 的字符串输入
我是 C++ 编程新手。我已经阅读了如何使用向量在SO问题中完成解析(Int tokenizer)。但是我尝试了以下方法对于数组。我只能从字符串中解析一个数字。如果输入字符串是“11 22 33 等”。
#include<iostream>
#include<iterator>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
int i=0;
string s;
cout<<"enter the string of numbers \n";
cin>>s;
stringstream ss(s);
int j;
int a[10];
while(ss>>j)
{
a[i]=j;
i++;
}
for(int k=0;k<10;k++)
{
cout<<"\t"<<a[k]<<endl;
}
}
如果我输入“11 22 33”
output
11
and some garbage values.
如果我已经初始化了 stringstream ss(“11 22 33”); 则它工作正常。我做错了什么?
I am new to c++ programming. I have read how parsing can be done in SO questions using vector(Int tokenizer).But I have tried the following for array. I am able to parse only one number from string. If input string is "11 22 33 etc".
#include<iostream>
#include<iterator>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
int i=0;
string s;
cout<<"enter the string of numbers \n";
cin>>s;
stringstream ss(s);
int j;
int a[10];
while(ss>>j)
{
a[i]=j;
i++;
}
for(int k=0;k<10;k++)
{
cout<<"\t"<<a[k]<<endl;
}
}
If I give input as "11 22 33"
output
11
and some garbage values.
If i have initialized stringstream ss("11 22 33");
then its working fine. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是:
将一个空格分隔的单词读入 s 中。所以只有 11 进入 s。
您想要的是:
或者您可以直接从
std::cin
读取数字The problem is that:
Reads one space separated word into s. So only 11 goes into s.
What you want is:
Alternatively you can read numbers directly from
std::cin
看起来 cin>>s 停在第一个空白处。试试这个:
It seems
cin>>s
stop at the first whitespace. Try this:我们可以使用 cin 通过提取运算符 (>>) 获取字符串,就像处理基本数据类型变量一样
cin >> mystring;
但是,正如前面所说,cin 提取一旦发现任何空格字符就会停止读取,因此在这种情况下,每次提取只能获取一个单词。
来自 http://www.cplusplus.com/doc/tutorial/basic_io/
所以你必须使用获取线()
We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables
cin >> mystring;
However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so in this case we will be able to get just one word for each extraction.
From http://www.cplusplus.com/doc/tutorial/basic_io/
So you have to use getline()