我有一个输入文件,每行有 3 个字段,类型为:string、double、double。有 15 行数据。
输入文件数据的格式为:
加德满都,-34、28
城市名称、低温、高温
....
...
..
很明显,根据输出,它没有获得线路上的第三个输入。
代码如下:
for (int index = 0; index < 15; index++)
{
getline(inFile, weatherInfo[index].city, ',');
inFile >> weatherInfo[index].low >> weatherInfo[index].high;
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
出于某种原因,这是我的输出:
Katmandu (-34, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
我知道我的程序能够读取其他行,因为当我添加
inFile.ignore(20);
到我语句的开头是它输出的循环
28
Perth (92, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
输出代码:
void ShowAll(int count) //Show entire data function
{
int x = 0; //loop through the index of city[], lowTemp[], highTemp[], and print them.
while (x < count)
{
cout << weatherInfo[x].city << " (" << weatherInfo[x].low << ", " << weatherInfo[x].high << ")" << endl;
x++;
}
cout << endl;
}
最佳答案
如果一行中的数据用逗号分隔那么你应该使用下面的方法
#include <sstream>
//...
std::string line;
for ( int index = 0; index < 15 && std::getline( inFile, line ); index++)
{
std::istringstream is( line );
getline( is, weatherInfo[index].city, ',');
std::string field;
if ( getline( is, field, ',') ) weatherInfo[index].low = std::stod( field );
if ( getline( is, field, ',') ) weatherInfo[index].high = std::stod( field );
}
您的代码存在的问题是,当您尝试读取 double 值并遇到逗号时会发生错误。在这种情况下,流的状态将是错误的,所有其他输入将被忽略。
您还应该检查在您使用的语言环境中 double 的点表示是什么。
关于c++ - 第一个索引后未填充结构数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27353534/