Search code examples
c++whitespaceistreamtrailing

Remove whitespace from input stream by only means of istream functions


Is there any way of to remove the trailing whitespace after entered a decimal? E.g.:

10        A

I want to catch the first character after the whitespace ends. (Which gotta be \n to be true. if not, then false

My attempt so far:

cout << "Please enter a number: ";
cin >> n;

if (cin.peek() == ' ')
    //Something to catch the whitespaces

if(cin.fail() || cin.peek() != '\n')
    cout << "Not a number." << endl;

else
    cout << "A number." << endl;

Possible to do that by functions in istream?

(I know cin.fail can do good deeds, but it still doesn't consider an input of 10A as a fail)


Solution

  • Thanks for your help. With strings it do be easy yes. Though not allowed to use it.

    Can be done by this simple method:

    cout << "Please enter a number: ";
    cin >> n;
    
    while (cin.peek() == ' ')
       cin.ignore(1,' ');
    
    if(cin.fail() || cin.peek() != '\n')
       cout << "Not a number." << endl;
    
    else
       cout << "A number." << endl;