Home > database >  While loop will only terminate if I use CTRL C on the terminal
While loop will only terminate if I use CTRL C on the terminal

Time:11-14

The prompt of the question is:

Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (for example, a space, carriage return, newline) or borders the beginning or end of the file.

I have successfully gotten the program to count how many words are in a file; no issues there.

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>

int main()
{
    char file_name[16];
    std::ifstream in_stream;
    int count = 0;
    char ch;
    bool lastWasWhite = true;
    std::string next;

    // Ask the user for the file name
    std::cout << "What is the name of the file? ";
    std::cin >> file_name;
    in_stream.open(file_name);

    // See if we can open the file
    if (!in_stream.is_open()) {
        std::cout << "Something went wrong when opening your file.";
        exit(1);
    }

    // Read the file, one character at a time
    while (in_stream >> next) {
        do {
            std::cin.get(ch);
        }
        while (ch != ' ' && ch != '\n' && ch != '\t');
          count;
    }
    
    in_stream.close();

    std::cout << "The file " << file_name << " contains " << count << " words." << std::endl;

    return 0;
}

The only problem is that the only way for the program, or I think the "while loop" to finish, is for me to hit CTRL C on the terminal so it force stops. Then I get the result I want.

terminal

This is my first post, so please let me know if there is any other information you would like to see.

CodePudding user response:

Your outer loop is reading words from the file and counting them just fine (operator>> handles the whitespace for you).

However, your outer loop is also running an inner loop that is reading user input from stdin (ie, the terminal). That is where your real problem is. You are waiting on user input where you should not be doing so. So, simply get rid of the inner loop altogether:

while (in_stream >> next) {
      count;
}

That is all you need.

  •  Tags:  
  • c
  • Related