我有一个程序,允许用户输入12个字符类型的字符初始化的元素,例如"991231066245“,我想比较第三个元素和第四个元素是否等于12。
例如:
char UserInput[20];
cout << "user input: ";
cin >> UserInput; //eg: 991231066245
//compare
int a = atoi(UserInput[2] + UserInput[3]); //something like this
if(a == 12){
cout << "yes";
}但是我可以通过使用UserInput2=\0得到UserInput & UserInput1,然后使用atoi(UserInput)进行比较,如果我加上UserInput4 = \0,那么我将得到4个元素,所以我想问一下,有什么方法可以做到吗?谢谢。
发布于 2019-06-06 16:48:05
这样如何:
if (UserInput[2] == '1' && UserInput[3] == '2')
{
std::cout << "yes\n";
}如果您必须转换为int,请使用std::string而不是char*,这非常简单:
#include <iostream>
#include <string>
int main()
{
std::string UserInput{ "991231066245" };
int a{ std::stoi(UserInput.substr(2, 2)) };
std::cout << a << '\n';
return 0;
}输出:
12https://stackoverflow.com/questions/56473871
复制相似问题