查找文件末尾时出现问题

Issue with finding the end of a file?

本文关键字:问题 文件 查找      更新时间:2023-10-16

从文件中读取输入时出现问题,计算每个单词中的字符数,然后将此计数输出到输出文件。

输入文件中的示例内容:一二三四五

正确的输出是:3 3 5 4 4

现在,如果在输入文件中我在"五"的末尾放置一个空格,则下面的代码可以工作。 如果我不放置这个空格,代码就会卡在嵌入的 while 循环中(见下文)。

有什么想法吗? 提前谢谢。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char c; //declare variable c of type char
    int count = 0; //declar variable count of type int and initializes to 0
    ifstream infile( "input.txt" ); //opens file input.txt for reading
    ofstream outfile( "output.txt" ); //opens file output.txt for writing
    c = infile.get(); //gets first character from infile and assigns to variable c
    //while the end of file is not reached
    while ( !infile.eof() )
    {
        //while loop that counts the number of characters until a space is found
        while( c != ' ' ) //THIS IS THE WHILE LOOP WHERE IT GETS STUCK
        {
            count++; //increments counter
            c = infile.get(); //gets next character
        }
        c = infile.get(); //gets next character
        outfile << count << " "; //writes space to output.txt
        count = 0; //reset counter
    }
    //closes files
    infile.close();
    outfile.close();
    return 0;
}

解决此问题的另一种方法是简化:

#include <fstream>
#include <string>
int main()
{
  std::string word;
  std::ifstream infile("input.txt");
  std::ofstream outfile("output.txt");
  while (infile >> word)
    outfile << word.size() << ' ';
}

修改内部的条件,同时:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char c; //declare variable c of type char
    int count = 0; //declar variable count of type int and initializes to 0
    ifstream infile( "input.txt" ); //opens file input.txt for reading
    ofstream outfile( "output.txt" ); //opens file output.txt for writing
    c = infile.get(); //gets first character from infile and assigns to variable c
    //while the end of file is not reached
    while ( !infile.eof() )
    {
        //while loop that counts the number of characters until a space is found
        while( c != ' ' &&  !infile.eof() )
        {
            count++; //increments counter
            c = infile.get(); //gets next character
        }
        c = infile.get(); //gets next character
        outfile << count << " "; //writes space to output.txt
        count = 0; //reset counter
    }
    //closes files
    infile.close();
    outfile.close();
    return 0;
}

通过将字符检查为:

while(fgetc(infile) != EOF){ //Rest code goes here }