c++ - fstream 的 getline() 工作了一点......然后中断

标签 c++

我有一个文本文件,其中包含一堆由换行符分隔的数字,如下所示: 123.25 95.12 114.12 等...

问题是,当我的程序读取它时,它只将数字复制到数组中直到第二个数字,然后用零填充其余元素。我试过使用定界符和忽略语句,但没有任何效果。这是代码。

编辑(这里是整个程序:)

#include <iostream>
#include <string.h>
#include <iomanip>
#include <fstream>

using namespace std;


struct utilityInfo
{
    char utility[20];
    double monthlyExpenses[12];
};

int main(){

utilityInfo Utility[3];

char charray[100];

fstream inFile;  
inFile.open("expenses.txt");
inFile.getline(charray, 7);
cout<<charray<<endl;
if(inFile.fail()) cout<<"it didnt work";

for(int i=0; i<12; i++)
{
    inFile.getline(charray,20);
    Utility[0].monthlyExpenses[i]=atof(charray);
}

for(int z=0; z<12; z++)
{
cout<<Utility[0].monthlyExpenses[z]<<endl;
}

inFile.close();


return 0;
} 

这是文本文件的样子:

207.14 
177.34
150.55
104.22
86.36
53.97
52.55
58.77
64.66
120.32
153.45
170.90

输出结果如下:

207.14
177.34
0
0
0
0
0
0
0
0
0
0

最佳答案

您文件中的第一个条目“207.14”实际上是“207.14”——(那里有一个空格)。您读取了 7 个字符,但将 ""留在那里,这意味着 istream::getline 在 inFile 上设置了失败位,这意味着您的后续 getlines 失败。

要解决此问题,请阅读足够的内容以到达换行符,删除空格和/或在您的第一个 getline 之后清除 inFiles failbit。

您还应该在您的 for 循环中添加一个检查,以处理 fail/bad/eof 位可能发生的任何错误。

关于c++ - fstream 的 getline() 工作了一点......然后中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10064735/

相关文章:

c++ - 在 Visual C++ (Windows) 中检测内存泄漏

c++ - 访问数组超出限制

c++ - 无论如何有一个 valgrind 消息 "Conditional jump or move depends on uninitialized value"可以是所谓的 'false positive'

c++ - OpenGL 二维旋转

c++ - 享元模式和 C++ 模板

c++ - 在库中包含具有外部 C 链接的函数

c++ - 如何从文件中读取整行(带空格)?

c++ - Geany intellisense 类似 C++ 的功能

c++ - cudaMallocPitch 和 cudaMemcpy2D

c++ - CMake 不再查找静态 Boost 库