检查输入是否是C ++中的数字或字符串 [英] Check if the input is a number or string in C++

查看:254
本文介绍了检查输入是否是C ++中的数字或字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码来检查输入(answer3)是一个数字或字符串,如果它不是一个数字,它应该返回Enter Numbers Only,但它返回相同的数字。请建议我一个解决方案。

I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return "Enter Numbers Only" but it returns the same even for numbers. Please suggest me a solution.

#include <iostream>
#include <string>
#include <typeinfo>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

using namespace std; 
int main ()
{

string ques1= "Client's Name :";
string ques2 = "Client's Address :";
string ques3 = "Mobile Number :";


char answer1 [80];
string answer2;
int answer3;


     cout<<ques1<<endl;    
     cin>>answer1;      

     cout<<ques2<<endl;    
     cin>>answer2; 

     cout<<ques3<<endl;
     cin>>answer3;



       if (isdigit(answer3))
       {
              cout<<"Correct"<<endl;     

              }

        else
        {
          cout<<"Enter Numbers Only"<<endl;  

            }

 system("pause>null");
 return 0;  







}


推荐答案

如果使用C ++ 98 ,可以使用 stringstreams #include< sstream> ):

std::string s = "1234798797";
std::istringstream iss(s);

int num = 0;

if (!(iss >> num).fail()) {
    std::cout << num << std::endl;
}
else {
    std::cerr << "There was a problem converting the string to an integer!" << std::endl;
}

如果您可以使用提升功能使用 lexical_cast #include < boost / lexical_cast.hpp> ):

std::string s = "1234798797";
int num = boost::lexical_cast<int>(si);//num is 1234798797
std::cout << num << std::endl;

如果您可以使用C ++ 11 内置 std :: stoi 函数来自< string>

std::string s = "1234798797";
int mynum = std::stoi(s);
std::cout << mynum << std::endl;

OUTPUTS:

1234798797

这篇关于检查输入是否是C ++中的数字或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆