【发布时间】:2014-02-21 16:20:03
【问题描述】:
用户引入了一个像“1 10 4 1 53”这样的字符串,我必须读取字符串中的所有数字。我怎样才能在 C++ 中做到这一点?
【问题讨论】:
-
这个问题和类似的问题已经在这里讨论过无数次了;你试过搜索吗?
-
关键字是“StackOverflow C++ 读取文件整数空格分隔”
用户引入了一个像“1 10 4 1 53”这样的字符串,我必须读取字符串中的所有数字。我怎样才能在 C++ 中做到这一点?
【问题讨论】:
如果您不关心速度,请使用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;
}
【讨论】:
只需将其放入istringstream 并使用普通的>>。
【讨论】:
您可以将输入作为字符串,然后您可以使用strtok() 对字符串进行标记以分隔字符串。
【讨论】: