【发布时间】:2020-10-08 03:43:04
【问题描述】:
我习惯了 Python,现在正在学习 C++,这对我来说有点复杂。如何修改输入以使其符合代码顶部注释中的描述?我试图包含 if (input[0]!='.' &&...) 但它只返回 0。我希望它作为数字的一部分包含在内。与输入的第一个字符之后的字符相同。
我也不知道如何用逗号分隔超过三位数的数字(显然是从数字的末尾开始)(所以 1000000 应该返回为 1,000,000)。
/*
* The first character can be a number, +, -, or a decimal point
* All other characters can be numeric, a comma or a decimal point
* Any commas must be in their proper location (ie, separating hundreds from thousands, from millions, etc)
* No commas after the decimal point
* Only one decimal point in the number
*
*/
#include <iostream>
#include <cmath>
#include <climits>
#include <string>
int ReadInt(std::string prompt);
int ReadInt(std::string prompt)
{
std::string input;
std::string convert;
bool isValid=true;
do {
isValid=true;
std::cout << prompt;
std::cin >> input;
if (input[0]!='.' && input[0]!='+' && input[0]!='-' && isdigit(input[0]) == 0) {
std::cout << "Error! Input was not an integer.\n";
isValid=false;
}
else {
convert=input.substr(0,1);
}
long len=input.length();
for (long index=1; index < len && isValid==true; index++) {
if (input[index]==',') {
;
}
else if (isdigit(input[index]) == 0){
std::cout << "Error! Input was not an integer.\n";
isValid=false;
}
else if (input[index] == '.') {
;
}
else {
convert += input.substr(index,1);
}
}
} while (isValid==false);
int returnValue=atoi(convert.c_str());
return returnValue;
}
int main()
{
int x=ReadInt("Enter a value: ");
std::cout << "Value entered was " << x << std::endl;
return 0;
}
【问题讨论】:
-
您可能想使用正则表达式来匹配这样的字符串。
-
我同意正则表达式是一个不错的选择。但是,我觉得我需要先掌握 C++ 的基础知识。有没有办法用简单的语法来做到这一点?使用类似于我可能拥有的东西?
-
如果要允许带小数的数字,则必须将小数点添加到
convert变量并使用atof(或std::stod)转换为双精度数。如果它不起作用,请使用调试器查看执行失败的地方。
标签: c++ validation input