找到文件结尾的问题?

时间:2014-04-07 01:08:55

标签: c++ file-io while-loop infinite-loop eof

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

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

正确的输出是: 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;
}

3 个答案:

答案 0 :(得分:3)

另一种解决方法是简化:

#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() << ' ';
}

答案 1 :(得分:0)

修改内在条件:

#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;
}

答案 2 :(得分:-3)

通过将字符检查为:

来检查EOF

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