C++ 只需在cpp中输入一个数字

C++ 只需在cpp中输入一个数字,c++,C++,我需要创建一个id号。例如:12345678 如果用户输入失败(包含字符),请立即删除字符。 例如:123a=>输入增益! 请帮帮我 我想这就是你想要的: #include <iostream> #include <string> #include <cctype> int main () { std::string input; bool valid; do { valid = true; std::cin >> i

我需要创建一个id号。例如:12345678 如果用户输入失败(包含字符),请立即删除字符。 例如:123a=>输入增益!
请帮帮我

我想这就是你想要的:

#include <iostream>
#include <string>
#include <cctype>

int main () {
  std::string input;
  bool valid;
  do {
    valid = true;
    std::cin >> input;
    for (char c : input)
      if (! std::isdigit( static_cast<unsigned char>(c) ) )
        valid = false;
  } while (! valid);
  // Here the string is guaranteed to be valid
}
#包括
#包括
#包括
int main(){
std::字符串输入;
布尔有效;
做{
有效=真;
std::cin>>输入;
for(字符c:输入)
如果(!std::isdigit(静态_cast(c)))
有效=错误;
}而(!有效);
//这里保证字符串是有效的
}

但是要注意,无论你想做什么,这个看起来都不是正确的方法。C++中有读数字的方法,这不是我推荐的。< /P>请分享你尝试过的一些代码并改进这个问题。也许这个答案(检查其他)可能帮助你把<代码> STD::ISDigie<代码> > <代码>未签名char < /> >,参见ch.c:输入???请解释一下。@ChristianHackl你说得对,很抱歉,我没注意到这是一个基于范围的for循环。看见这将迭代字符串的字符input@Sevis:你的编辑使情况更糟。您仍然没有将参数强制转换为
unsigned char
,这对于防止UB是必要的,但是结果是错误的。更糟糕的是,这是一个C型演员。整行代码应该是这样的:
if(!std::isdigit(static_cast(c))