想要使用sstream解析int类型的字符串输入

want to parse string input for int using sstream

本文关键字:类型 字符串 输入 int 解析 sstream      更新时间:2023-10-16

我是c++编程新手。我读过如何解析可以在SO问题中使用向量(Int标记器)。但我已经尝试了以下数组。我只能从字符串中解析一个数字。如果输入字符串为"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");,那么它的工作很好。我做错了什么?

问题是:

cin>>s;

将一个空格分隔的单词读入s,因此s只有11。

你想要的是:

std::getline(std::cin, s);

或者您可以直接从std::cin

读取数字
while(std::cin >> j) // Read a number from the standard input.

似乎cin>>s停止在第一个空白。试试这个:

cout << "enter the string of numbers" << endl;
int j = -1;
vector<int> a;
while (cin>>j) a.push_back(j);

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.

从http://www.cplusplus.com/doc/tutorial/basic_io/

必须使用getline()

string s;
cout<<"enter the string of numbers n";
getline(cin, s);