检查输入字符串以查看它是否是C ++中的数字

时间:2016-03-25 16:01:27

标签: c++

我是C ++的新手, 请问有没有办法检查输入字符串是否为数字? 如果是数字,请将其更改为整数。

我知道我们可以使用atoi或stoi。

但是我们如何在一个函数中创建它呢?

5 个答案:

答案 0 :(得分:0)

  1. std::istringstream
  2. 构建std::string
  3. 从中提取一个数字。如果提取成功,请使用该数字。如果没有,继续下一步。
  4. std::string s = "123";
    std::istringstream str(s);
    int n;
    if ( str >> n )
    {
       // Extraction is successful.
       // Use n.
    }
    

    进一步的启示

    为了使您的程序更加健壮,您可以添加进一步的检查以确保:

    “123FAST”不被视为整数 “123.56”不被视为整数 “123.56xyz”不被视为整数。

    std::string s = "123";
    std::istringstream str(s);
    int n;
    if ( str >> n )
    {
       // Extraction is successful.
       // Add another check.
    
       // Get the next character.
       // It has to be a whitespace character or EOF for the input
       // to be an integer.
       // If it is neither, don't accept the input as an integer.
       std::istream::int_type c = str.get();
       if ( std::isspace(c) || str.eof() )
       {
          // Use n.
       }
    }
    

答案 1 :(得分:-1)

您只需检查输入字符串中的每个字符是否为数字,我有一个简单的示例来解决您的问题:

#include <stdio.h>
#include <string.h>

bool is_number(const char * s)
{
    int length = strlen(s);
    for (int i = 0; i < length; i++)
    {
        if (s[i] < '0' || s[i] > '9')
            return false;
    }
    return true;
}

int main()
{
    printf("Enter a string: ");
    char myString[10];
    gets(myString);
    if (is_number(myString))
        printf("%s is a number", myString);
    else
        printf("%s is not a number", myString);
}

答案 2 :(得分:-1)

我认为你甚至不需要检查。根据C ++ API:

  

如果str中的第一个非空白字符序列不是a   有效的整数,或者如果没有这样的序列,则可能   str为空或仅包含空格字符,不包含转换   执行并返回零。

请参阅: http://www.cplusplus.com/reference/cstdlib/atoi/

-

所以,你应该能够做到:

// Convert the string
int value = atoi( myString.c_str() );

if ( value == 0 )
{
    // The string was not a valid integer
}
else
{
    // The string was a valid integer
}

答案 3 :(得分:-1)

&#39; ISNUM()&#39;下面的函数检查给定的字符串是否仅由数字组成。但是,如果数字非常大,它可能无效。

#include <bits/stdc++.h>
using namespace std;
bool isnum(string str){
    for(int i=0;i<str.length();i++){
        if((str[i]<'0') || (str[i]>'9'))return false;
    }
    return true;
    }
int main() {
    // your code goes here
    int n=0,r=1;
    string num;
    cin>>num;
    if(isnum(num)){
        for(int i=num.length()-1;i>=0;i--){
            n+=(r)*(int)(num[i]-'0');
            r*=10;
        }
    cout<<n;
    }
    return 0;
}

答案 4 :(得分:-1)

您可以检查字符串中是否有任何非数字字符:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main()
{
    std::string test;

    std::cin >> test;
    if(std::find_if(test.begin(), test.end(), [](auto x){return !isdigit(x);}) == test.end())
        std::cout << "its a number" << std::endl;
    else
        std::cout << "not a number" << std::endl;
}
相关问题