【发布时间】:2012-07-21 06:11:51
【问题描述】:
正如标题所说,我正在从标准输入读取一串整数。我试图读取的数据以以下形式出现在文本文件中:
3
4
7 8 3
7 9 2
8 9 1
0 1 28
etc...
前两行总是只有一个数字(没有问题!),接下来的每行都有 3 个数字。该文件作为标准输入重定向到我的程序(myprogram
我已经尝试了很多东西,但都无法成功地做到这一点!看起来很简单,但我一直在纠结应该在哪里(或如何)转换为整数。这是我最近的尝试:
int main()
{
string str, str1, str2;
int numCities;
int numRoads, x, y, z;
cin >> numCities >> numRoads;
cout << numCities << " " << numRoads << endl;
//getline(cin, str1);
while( getline(cin, str))
{
char *cstr;
cstr = new char[str.size()+1];
strcpy(cstr, str.c_str());
x = atoi(strtok(cstr, " ")); //these will be stored in an array or something
y = atoi(strtok(NULL, " ")); //but right now i just want to at least properly
z = atoi(strtok(NULL, " ")); //store the appropriate values in these variables!
}
return 0;
}
我尝试使用 atoi 时出现段错误...
提前致谢!
【问题讨论】:
-
@Kevin :
while (cin.good())是一种反模式。 @Wakka,你想单独存储每一行的数字,还是只存储所有数字的一个大列表? -
@ildjarn:
while (cin >> x >> y >> z)呢? -
@Victor :那肯定是一个改进。 ;-]
标签: c++ string parsing integer