如何读取C ++中用空格分隔的字符串?

时间:2014-02-21 16:20:03

标签: c++ string

用户引入了一个字符串,如“1 10 4 1 53”,我必须读取字符串中的所有数字。我怎么能用C ++做到这一点?

3 个答案:

答案 0 :(得分:0)

只需将其放入istringstream并使用普通>>

答案 1 :(得分:0)

如果您不关心速度,请使用stringstream

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int
main()
{
  string str("1 10 4 1 53");
  stringstream ss(str);
  int n;
  while (ss >> n)
    cout << n << endl;
  return 0;
}

答案 2 :(得分:0)

您可以将输入作为字符串,然后使用strtok()对字符串进行标记,以分隔字符串。