Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

c++ - i have a problem to check wheather the input is string or number

trying to find out: if the user enter a string or a number , but when trying to enter a number it just enter an inifiti loop , and just print "enter your name ",and i want if its a string after entering the loop , to just get out the loop.

#include <iostream>
#include<sstream>
#include<cmath>
#include<iomanip>
using namespace std;

 main()
{
  string name;

  cout<<"enter your name :";
  cin>>name;

  stringstream s;
  int x;
  s<<name;
  s>>x;
  while(x!=0)
  {
    cout<<"enter your name :";
    cin>>name;
    s<<name;
    s>>x;
    
  }


   return 0;
}
question from:https://stackoverflow.com/questions/65877540/i-have-a-problem-to-check-wheather-the-input-is-string-or-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If a stream can't parse the wanted input to the variable, it will set an internal fail flag.

This flag can be checked by using the stream in a condition.

And the extraction operator returns a reference to the stream.

Put together you can do something like

while (s >> x)
{
    // String starts with a number...
    s.clear();  // Clear fail state flag
    // TODO: Ask for new input, set contents of s
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...