Home > Enterprise >  How To Stop C From Repeating Itself?
How To Stop C From Repeating Itself?

Time:11-20

Sorry for the poor question but I really do not know what is happening.

while (true) {
        string choice;
        cout << ">>> ";
        cin >> choice;
        if (choice == "hi") {
                cout << "Whats up?" << endl;
        } else {
                cout << "error" << endl;
        }
}

If I compile this and then input "hi" it will show

>>> hi
Whats up?
>>> 

but if I do "hi hi"

>>> hi hi
Whats up?
>>> Whats up?
>>> 

It will show that. Why is it showing Whats up? twice instead of the error message?

CodePudding user response:

The problem is that std::cin is used to read either a number that is compatible with the type of the variable, or a single word at a time. Technically, you're using formatted input operator>> which discards leading whitespace and will also stop reading when it encounters a whitespace/invalid input.

To solve this, replace cin >> choice; with:

std::getline(cin, choice);

This will read until '\n' is encountered, and now we're using unformatted input.

So, the modified code looks like:

while (true) {
    string choice;
    cout << ">>> ";
    std::getline(cin, choice);//i modified this 
    if (choice == "hi") {
        cout << "Whats up?" << endl;
    } else {
        cout << "error" << endl;
    }
}

You can try out the code here.

CodePudding user response:

As soon as std::cin reads a space character (this ' '), it won't consider any more characters that come after that space char as part of the input. So the next time it reads the buffer it will read the second "hi" and insert it to choice. It is like you're entering "hi" and pressing enter key and then doing it again. You will see "Whats up?" being printed twice.

Use std::getline(std::cin, choice); to get the full input even if there are space or tab characters in between the other characters.

If you want something more error-safe then this function might be helpful:


#include <iostream>
#include <limits>


void getCharInput( char arr[], const std::streamsize streamSize )
{
    std::cin.putback( '\n' );
    std::cin.clear( );
    std::cin.ignore( std::numeric_limits<std::streamsize>::max( ), '\n' );
    std::cin.getline( arr, streamSize );
}

int main()
{
    constexpr std::streamsize streamSize { 11 }; // 11 as an example ( 10 for actual chars plus 1 for '\0' )
    char inputBuffer[ streamSize ] { };

    getCharInput( inputBuffer, streamSize );

    std::cout << "Input is: <" << inputBuffer << ">" << '\n';
}

Only 11 chars (including the null-terminator '\0') will be read and stored in inputBuffer.

  •  Tags:  
  • c
  • Related