【发布时间】:2014-01-29 21:35:06
【问题描述】:
我的输入格式:
192,21,4 33,2,1 23,7,61
我只想获得数字。
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
int strtoint(const std::string str){ //converting the string to integer
float a = str.length();
int result = 0;
for(int i=1; i<=str.length(); i++){
result+=(str[i-1]-'0')*pow(10,(a-1));
a--;
}
return result;
}
int main ()
{
string name;
string segment;
while(getline (cin,name, ' ')){
stringstream test(name);
while(getline(test, segment, ','))
{
cout << segment <<" "<<strtoint(segment)<<endl;
}
}
return 0;
}
我没有获得最后一个 (61)。所以输出是 192 21 4 33 2 1 23 7。
如何获得所有数字?
【问题讨论】:
-
我刚刚在 ideone 中运行了这个,得到了所有 9 个整数,打印了两次,每个在单独的行上:ideone.com/lvzTpq
-
@notch,你是否也在输出结束时得到 572?我相信那是因为 getline 在 61 结尾处将换行符(“\n”)添加到分段字符串。如果根本没有出现,也许 getline 不知道返回,因为它没有收到空格(“” ) 也不是换行符 ("\n")
-
Derek 的输入在 61 之后添加了换行符。
getline不关心 \n,还删除了分隔符。 -
是的,我在输出的末尾也得到了 572,我们可以做些什么来解决?