C++ 读取整数时检查字母
我正在制作一个需要用户输入生产订单(7位数)的应用程序,如下所示:C++ 读取整数时检查字母,c++,windows,c++11,type-conversion,C++,Windows,C++11,Type Conversion,我正在制作一个需要用户输入生产订单(7位数)的应用程序,如下所示: int order = 0; cout << "Insert the order number: "; cin >> ordem; bool isLetter(int a) { string s = to_string(a); for (int i = 0; i < s.size()-1; i++) { if (isdigit(s[i]))
int order = 0;
cout << "Insert the order number: ";
cin >> ordem;
bool isLetter(int a)
{
string s = to_string(a);
for (int i = 0; i < s.size()-1; i++)
{
if (isdigit(s[i]))
{
return false;
}
else
return true;
}
}
bool isLetter(string s)
{
// Return true if the given string contains at least one letter.
for (size_t i = 0; i < s.size(); i++)
if (!isdigit(s[i]))
return true;
// Return false if there are only digits in the given string.
return false;
}
int顺序=0;
cout>ordem;
如何防止用户输入字母?比如“I2345G789”
这样,我的应用程序就进入了一个无限循环。我在考虑使用这样的函数:
int order = 0;
cout << "Insert the order number: ";
cin >> ordem;
bool isLetter(int a)
{
string s = to_string(a);
for (int i = 0; i < s.size()-1; i++)
{
if (isdigit(s[i]))
{
return false;
}
else
return true;
}
}
bool isLetter(string s)
{
// Return true if the given string contains at least one letter.
for (size_t i = 0; i < s.size(); i++)
if (!isdigit(s[i]))
return true;
// Return false if there are only digits in the given string.
return false;
}
bool-isleter(inta)
{
字符串s=至_字符串(a);
对于(int i=0;i
然后:
if (isLetter(order))
{
cout << "Insert only numbers \n";
}
if(指令)
{
cout我猜您的代码周围有一个循环,以便在订单号包含非数字时再次请求订单号,例如:
while(...)
{
int order = 0;
cout << "Insert the order number: ";
cin >> order;
}
请注意,它应该是i
而不是i
。也许您应该将函数isLetter()
重命名为hasLetter()
,因为那会更正确。可能是@Wimmel的重复这给出了一个不同的解决方案,但无助于OP理解他最初的错误。我不会将此标记为重复。为什么要否决我的问题?你们太严格了!noob怎么能那样学习呢?回答得好!我假设I
?因为在我看来,这会阻止我获得最后的字符,即'\0'
。函数size()
在计算字符时排除\0
。如果字符串是abc
,那么它的长度(size)是3而不是4,即使为了正确终止字符串而附加了\0
。很好,我不知道。再次感谢!现在我应该问你:为什么使用size\u t I
而不仅仅是int
?函数size()
返回类型size\u t
。现在这通常是一个无符号的64位整数。如果您只使用int
,编译器应该给您一个警告(如果您打开了警告)您正在比较有符号类型和无符号类型。而且,int
通常只有32位。因此,对于非常大的结构,您可能会出现溢出。但是,unsigned int
也适用于您的用例;)