c++ - 第一个索引后未填充结构数组索引

标签 c++ arrays loops struct fstream

我有一个输入文件,每行有 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/

相关文章:

c++ - 未找到 GetAddrInfo 标识符

java - 类和对象的概念

c++ - boost lexical_cast 抛出异常

c++ - boolean 函数

java将数组不同为特定值

python - 如何使用 numpy 在二维数组上执行最大/均值池化

java - 拆分字符串数组导致数组索引超出范围

linux - 从 `find` 开始循环文件名?

java - 使用嵌套的 for 循环检查数字是否为素数;如果是这样,将它们添加到集合中——不使用 isPrime 方法

loops - 函数内部递归 - haskell