验证字符串是否为全数字
Validating a string to be all digits
嗨,我在验证此字符串是否都是小数时遇到问题,即使我输入 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++)
在循环条件下,您需要将i
与In1.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 )
这些功能通常没有什么特别或戏剧性的,它们将操作应用于开始-结束序列中的每个元素。
您有find
、count
、copy
和generate
等等。 他们的目的是澄清您的 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;
}
- 用于检查数字是否有数字或可被该数字的值整除的程序
- 如何使用递归检查数字是否有重复数字?
- 查找数字是否为 2 的幂的时间复杂度
- 将 C 函数转换为 C++ 以检查数字是否有效
- 检查数字是否为素数的算法
- 在C/C++中检查数字是否为整数(不带scanf/gets/etc)
- 如何以更有效的方式检查一个数字是否是素数?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 如何检查字段中输入的数字是否重复
- 查看数字是否包含在未排序的双数字间隔内的最有效方法?
- 检查数字是否已在数组中的程序
- 编写一个函数,用递归函数检查数字是否是正方形
- 使用模量来找出数字是否可以除去不起作用的变量
- 查找数字是否为素数 c++
- 如何测试某些数字是否沿区间均匀分布?
- 这是确定两个数字是否具有相同奇偶校验的正确方法
- 如何检查 stdin 中的数字是否小于给定类型的数字限制
- 更好的算法来检查一个数字是否既不是素数也不是单个素数的幂
- 如何在不使用数学的情况下知道一个数字是否是回文
- 验证每个数字是否在特定条件下