Remove whitespace from input stream by only means

2019-06-14 09:32发布

问题:

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)

回答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";


回答2:

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.



回答3:

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;