验证字符串是否为全数字

Validating a string to be all digits

本文关键字:数字 是否 字符串 验证      更新时间:2023-10-16

嗨,我在验证此字符串是否都是小数时遇到问题,即使我输入 9999,它仍然告诉我我的 if 语句是假的。我认为这是一个错字,但我不知道在哪里。

cout<<"Enter a very large number"<<endl;
cin>>In1;                            //inputs a string
for(int i=0; 0<In1.length();i++){    //the loop that goes thru each index
    if (!(isdigit(In1[i]))){         //validates each index
        //tells the user to try again
        cout<<"You did not enter a valid input, please try again"<<endl;
        In1="";
        cin>>In1;
        i=0;//starts the loop over if reached
    }
}

不断收到"您没有输入有效的输入,请重试",无论我输入正确还是错误。

for(int i=0; 0<In1.length();i++){

看看你做了什么?更改为

for(int i=0; i<In1.length();i++)

在循环条件下,您需要将iIn1.length()进行比较。

你可能想改变

0<In1.length()

i<In1.length()

使用

#include<algorithm>
if ( std::find_not_if( in1.begin(), in1.end(), isdigit ) != in1.end() ){ ...

可能阻止了这一不幸事件,并且意图也非常明确。双_not/!=稍微混淆了它,但仍然如此。

有相当多的方便算法,取代了简单 for- 语句的常见用途。 他们中的大多数都在表格上

do_this( where_to_start, where_to_end, do_this_operation )

这些功能通常没有什么特别或戏剧性的,它们将操作应用于开始-结束序列中的每个元素。

您有findcountcopygenerate等等。 他们的目的是澄清您的 for-陈述的意图。 您可以在 http://en.cppreference.com/w/cpp/algorithm 找到完整列表

你几乎肯定会发现,随着时间的推移,你越来越擅长将代码的不同部分分离到它们各自提供的功能中。使调试和以后的修改变得相当容易。

正如长颈鹿船长指出的那样,它还使代码的意图更加清晰 - 这只会使阅读代码更容易和更快。

我没有使用 std::find_not_if,而是选择使用您选择的方法(基于假设重要的是知道如何获得正确答案,而不是简单地提供正确答案 - 好吧,我不知道find_not_if的存在:grin:)你会看到我已经把它塞进了它自己的函数中,我从main调用它。该函数也只执行一个任务 - 检查字符串的有效性。任何提示用户输入此文本的尝试,在出现错误时重新提示,最后对正确的输入采取行动,都是调用isValidNumericalString的代码的唯一责任 - 没有理由不能将这些函数放入它们自己的函数中,而不是拥有单个大型主体。

#include <iostream>
using namespace std;
// returns true if all characters in string are numerical (0-9)
bool isValidNumericalString(string inputString)
{
    int i, n = inputString.length();
    for (i=0; i<n; i++)
        if ( !isdigit(inputString[i]) )
            return false;
    return true;
}
int main()
{
    string In1;
    cout << "Enter a very large number (digits 0-9 only. 10e1 is unacceptable): ";
    cin >> In1;
    while (!isValidNumericalString(In1))
    {
        cout << "You did not enter a valid input, please try again :p" << endl;
        cout << "Enter a very large number (digits 0-9 only. 10e1 is unacceptable): ";
        cin >> In1;
    }
    cout << "Congratulations - '" << In1 << "' is a valid string representation of a number" << endl;
    return 0;
}