0

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)

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
user2180833
  • 156
  • 2
  • 11
  • Just get the whole line and you should find the resulting string much better to retrieve that information from. – chris Mar 28 '13 at 04:17
  • Duplicate of http://stackoverflow.com/questions/710604/how-do-i-set-eof-on-an-istream-without-reading-formatted-input – Stuart P. Bentley Apr 12 '16 at 06:05

3 Answers3

1

As @chris said, you really want to start by reading a whole line, then doing the rest of the reading from there.

std::string line;
std::getline(cin, line);

std::stringstream buffer(line);

buffer >> n;

char ch;
if (buffer >> ch) 
    cout << "Not a number";
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

I am a little confuse by what your trying to do. Are you saying your trying to avoid white spaces?

cin skips those... it is a valid blank separator like tab or newline. If you do:

int A(0), B(0);

std::cin >> A >> B;

the numbers entered will go in A until you type a space, then they will go in B.

If you are using strings and want to concatenate them into one without spaces;

std::string A, B, C;
std::string final;

std::cin >> A >> B >> C;

std::stringstream ss;
ss << A << B << C;
final = ss.str();

However, like Jerry mentioned, if your dealing with strings, you can just do std::getline() which will give you possibly less headaches.

Oria
  • 118
  • 10
0

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;
user2180833
  • 156
  • 2
  • 11
  • 5
    That `while` loop can be replaced by a call to [**`std::cin >> std::ws;`**](http://en.cppreference.com/w/cpp/io/manip/ws). – David G Jan 19 '14 at 16:52
  • 1
    @0x499602D2 You got that in an answer someplace? That's the answer that I came here looking for, and I'd like to upvote it. – Jonathan Mee Feb 11 '15 at 13:36
  • @JonathanMee I added it as an answer to this version of the same question I posted in 2009: https://stackoverflow.com/questions/710604/how-do-i-set-eof-on-an-istream-without-reading-formatted-input – Stuart P. Bentley Jul 20 '22 at 20:52