【问题标题】:want to parse string input for int using sstream想使用 sstream 为 int 解析字符串输入
【发布时间】:2011-12-15 07:44:04
【问题描述】:

我是 C++ 编程的新手。我已经阅读了如何使用向量(Int tokenizer)在 SO 问题中进行解析。但是我已经尝试了以下数组。我只能从字符串中解析一个数字。如果输入字符串是“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"); 那么它工作正常。我做错了什么?

【问题讨论】:

    标签: c++ stringstream


    【解决方案1】:

    问题是:

    cin>>s;
    

    将一个空格分隔的单词读入 s。所以只有 11 进入 s。

    你想要的是:

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

    您也可以直接从std::cin 读取数字

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

    【讨论】:

      【解决方案2】:

      似乎cin&gt;&gt;s 停在第一个空格处。试试这个:

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

      【讨论】:

        【解决方案3】:

        We can use cin to get strings with the extraction operator (&gt;&gt;) as we do with fundamental data type variables

        cin &gt;&gt; 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);
        

        【讨论】:

          猜你喜欢
          • 2013-09-26
          • 1970-01-01
          • 1970-01-01
          • 2011-06-25
          • 2018-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多