C++ getline() 和文件 EOF

标签 c++

这个问题困扰了我一个晚上,谢谢!

此代码将文件中的最后一行写入两次。为什么?

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
const int strSize = 1000;
int main(int argc,char *argv[])
{
    ifstream infile(argv[1]);
    if(!infile)    cerr<<"infile error!"<<endl;
    ofstream outfile(argv[2]);

    int sequenceNum = 1;
    char str[strSize];
    while(infile){
        infile.getline(str,strSize);
        if(sequenceNum>469)
            str[0] = '2';
        else if(sequenceNum>67)
            str[0] = '4';
        else if(sequenceNum>1)
            str[0] = '1';
        else
            str[0] = '3';
        outfile<<str<<endl;
        ++sequenceNum;
    }
    return 0;
}

infile.getline(str,strSize);之后,strNULL,如果不修改str,为什么为null?但在 if(sequenceNum>469) 之后,str 成为最后一行。

这段代码只写最后一行一次。

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
const int strSize = 1000;
int main(int argc,char *argv[])
{
    ifstream infile(argv[1]);
    if(!infile)    cerr<<"infile error!"<<endl;
    ofstream outfile(argv[2]);

    int sequenceNum = 1;
    char str[strSize];
    while(infile){
        infile.getline(str,strSize);
        if(strlen(str) != 0){//The key is this sentence.
            if(sequenceNum>469)
                str[0] = '2';
            else if(sequenceNum>67)
                str[0] = '4';
            else if(sequenceNum>1)
                str[0] = '1';
            else
                str[0] = '3';
            outfile<<str<<endl;
            ++sequenceNum;
        }
    }
    return 0;
}

最佳答案

问题是当 infile.getline 读取最后一行时(即读取到 EOF),while(infile) 仍将计算为真,从而导致循环再次运行。但是,由于 infile 读取了整个文件,infile.getline 将失败,并且 str 将变为空字符串。但是,由于您的原始代码覆盖了第一个字符,它摆脱了空终止符,因此它最终重用了上次的内容。

相反,你想要这样的东西:

while (infile.getline(str, strSize)) {
    if (sequenceNum>469)
    ...
}

关于C++ getline() 和文件 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971593/

相关文章:

c++ - 在 cmd pmt 中执行带空格的文件名 从 C++ 程序传递

c++ - i18n 剥离非字母数字字符的友好方式

c++ - void(int) 和 void (*)(int) 之间的区别

c++ - 如何将矩阵因式分解为核矩阵的乘积?

c++ - 在异常 C++ 中抛出语法

C++:setsockopt() 可以被信号忽略吗?

c++ - 声明一个接受泛型迭代器的函数

c++ - std::istream 运算符异常重置/不抛出

c++ - "no matching function for call to"让我感到困惑

c++ - 使用构造函数初始化类中的指针