Search code examples
c++ifstreamgetline

Matching word c++ program using getline() running infinitely?


I am learning c++ so bear with me and apologize for any idiocy beforehand.

I am trying to write some code that matches the first word on each line in a file called "command.txt" to either "num_lines", "num_words", or "num_chars".

If the first word of the first line does not match the previously mentioned words, it reads the next line. Once it hits a matching word (first words only!) it prints out the matching word.

Here is all of my code:

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

using namespace std;

ifstream comm_in("commands.txt"); // opens file
string command_name = "hi"; // stores command from file


bool is_command() {
    if (command_name == "num_words" || command_name == "num_chars" || command_name == "num_lines") {
        return true;
    } else {
        return false;
    }
}


// FIND a first word of a line in file THAT MATCHES "num_words", "num_chars" or "num_lines"
void get_command() {

    string line;
    char c;

    while (!is_command()) { // if command_name does not match a command

        // GET NEXT LINE OF FILE TO STRING
        getline(comm_in, line);

        // SUPPOSED TO GET THE FIRST WORD OF A STRING (CANT USE SSTREAM)
        for (int i = 0; i < line.size(); i++) { // increment through line
            c = line[i]; // assign c as index value of line

            if (c == ' ' || c == '\t') { // if c is a space/tab
                break; // end for loop
            } else {
                command_name += c; // concatenate c to command_name
            } // if
        } // for
    } // while
    return;
}

int main() {

    get_command();
    cout << command_name; // supposed to print "num_lines"
}

The contents of the command.txt file:

my bear is happy
and that it
great ha
num_lines sigh

It compiles properly, but when I run it in my terminal, nothing shows up; it doesn't seem to ever stop loading. How can I fix this?


Solution

  • If something goes wrong and you reach the end of file the loop will never stop. You should change getline(comm_in, line) to if(!getline(comm_in, line)) break;, or better yet, use that as the condition for the loop.

    You also have to reset command_name for each pass:

    while(getline(comm_in, line))
    { 
        command_name = "";
        for(int i = 0; i < line.size(); i++)
        { 
            c = line[i]; 
            if(c == ' ' || c == '\t') 
                break; 
            else 
                command_name += c; 
        } 
        if(is_command())
            break;
    }