如何查看char类型?我的变量输入需要是一个字符,因为它包含字母和数字。 如果我使用 string 而不是 char,while 没有错误,但 cin.getline(input,10) 有错误
char input[10];
while(input != "1") //Error: result of comparison against a string literal is unspecified(use strncmp //instead)
{
cin.getline(input, 10);
}
最佳答案
在表达式中(很少有异常(exception),例如在 sizeof 运算符中使用它们时)数组被隐式转换为指向其第一个元素的指针。
在这种情况下
while(input != "1")
有数组第一个字符的比较地址input
和字符串文字的第一个字符 "1"
.
改用标准 C 函数 strcmp
在 header 中声明 <cstring>
.
注意代码片段中的数组 input
未初始化。因此,在将它与某些东西进行比较之前,您必须对其进行初始化。
关于c++ - char类型声明和验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57995914/