Search code examples
c++loopswhile-loopstdinfgets

I want my program to stop accepting input from console when I type STOP in console C++ Program


I am making a C++ program which accepts input from user (even \n) is required but the program should stop when I type STOP, so can anyone help me out. Earlier I was using getline but that also got some issue like when I enter \n two (hit enter two times) it stops the whole code.

So can anyone guide me what to do, I want to capture whole input until user types STOP in console.

Thank you.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout<<"Main Started\n";
        char array[10];
        string str;
    
        while(fgets(array,sizeof(array),stdin))
        {
            str = (string) array;
            if(str=="STOP")  // This line is not getting executed. Also tried strcmp but of no use
                break;
           
        }
    
        cout<<"\nMain Ended\n";
        return 0;
    }

Solution

  • fgets() includes '\n' in the output, if the read is terminated by ENTER, so you need to check for that, eg:

    while (fgets(array, sizeof(array), stdin) != NULL)
    {
        str = array;
        if (str == "STOP" || str == "STOP\n")
            break;
    } 
    

    Or:

    while (fgets(array, sizeof(array), stdin) != NULL)
    {
        if (strcmp(str, "STOP") == 0 || strcmp(str, "STOP\n") == 0)
            break;
    } 
    

    std::getline() (and std::istream::getline()), on the other hand, do not include the terminating '\n' in the output:

    while (getline(cin, str))
    {
        if (str == "STOP")
            break;
    }