문제

having an issue reading input from a file, counting the amount of characters in each word, then outputting this count to an output file.

example content in input file: one two three four five

correct output would be: 3 3 5 4 4

Now the code below works if in the input file I put a blank space at the end of 'five'. If i don't put this empty space, the code gets stuck in the embedded while loop (see below).

Any thoughts? Thanks in advance.

#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;
}
도움이 되었습니까?

해결책

Another way of solving this is to simplify:

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

다른 팁

Modify the condition of the inner 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 != ' ' &&  !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;
}

Check EOF by checking characters as:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top