Sachin Khetarpal
Sachin Khetarpal

Reputation: 13

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

Upvotes: 1

Views: 1362

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16448

You can use getline:

#include <iostream>
#include <string>

int main() {
    std::cout << "Main Started\n";
    std::string str;

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

    std::cout << "\nMain Ended\n";
    return 0;
}

or operator>>

#include <iostream>
#include <string>

int main() {
    std::cout << "Main Started\n";
    std::string str;

    while(std::cin >> str) {
        if(str == "STOP")  
            break;
    }

    std::cout << "\nMain Ended\n";
    return 0;
}

Upvotes: 3

Remy Lebeau
Remy Lebeau

Reputation: 598194

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

Upvotes: 1

Related Questions