我正在编写一个程序,用户可以在其中输入他们想要的任何字符串,除非他们在字符串之前输入整数,否则它将是有效的。例如:
input: hi
output: hi is valid
input: 1hi
output: 1hi is invalid. It starts with a number
这就是我到目前为止所拥有的,但是如果我输入"hi",它会继续打印出"hi是有效的",如果我输入1hi,它会继续打印出"hi是有效的"。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
string input;
int main()
{
while (input != "quit")
{
cin >> input;
if (input == "1" + input)
cout << input << "in not valid. Reason: Started with a number.";
cout << input << " is valid.n";
}
return 0;
}
任何帮助,不胜感激。
答案已解决。使用ISdigit作为问题的解决方案。
类似的东西?
:if (input[0] >= 48 && input[0] <= 57) {
std::cout << input << " is not valid";
}
通过查看 ASCII 表,我认为这将起作用。
编辑 - (input == "1" + input)
永远不会是真的。
您可以使用 isdigit:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
string input;
int main()
{
while (input != "quit")
{
cin >> input;
if (isdigit(input.at(0)))
cout << input << "in not valid. Reason: Started with a number.";
else
cout << input << " is valid.n";
}
return 0;
}