为什么我不能继续使用 std::cin 向同一变量输入其他值?
Why I can't proceed to enter other values to the same variable with std::cin?
当我输入group_input变量的值时,程序完成,并且无法输入fio_input变量的值。如果我输入一个短值,我可以继续输入fio_input变量的值。有什么问题?
#include <iostream>
using namespace std;
int main()
{
unsigned char group_input, fio_input, result[7] = {0, 0, 0, 0, 0, 0, 0};
cout << "n Enter your group name: ";
cin >> group_input;
cout << "n Enter your full name: ";
cin >> fio_input;
}
您要一个名称,这是 char
s -a std::string
的数组。
#include <iostream>
#include <string>
int main(){
std::string group_input, fio_input;
std::cout << "n Enter your group name: ";
std::cin >> group_input;
std::cout << "n Enter your full name: ";
std::cin >> fio_input;
}
您不应该在此处阅读use namespace std;
。
另外,如果要输入空格名称,请改用std::getline(std::cin, str);
。因为如果您std::cin
"Roger Jones"
到fio_input
,它将仅保存"Roger"
当您读取char
变量时,系统将读取字符。单个char
只能存储一个字符,所以这就是读取的内容。
如果给出多字符输入,则第一个字符将存储在group_input
中,第二个字符将存储在fio_input
中。
如果您想阅读字符串(这似乎是您想要的),则使用std::string
。
如果要避免缓冲区溢出,则使用std::string
尤其重要。C 没有数组的边界检查。
在此行中
cin >> group_input;
您从标准输入中读取并将结果写入unsigned char
变量。将读取多少个字节?这取决于上线引用的过载的operator >>
。在您的情况下,两个"输入线"都调用了unsigned char
的过载,因为此数据类型只能存储一个字节,因此它读取一个字节。因此,您可以为两个变量输入一个字符名称,也可以将group_input
和fio_input
的数据类型更改为其他内容,例如。std::string
。在这种情况下,调用了operator >>
超载,将任何内容读取到下一个whitespace(但不包括它)字节,其中" Whitespace Byte"包括Tab,Newline等。
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 堆栈中大小变量输入错误 (C++)
- 如何使用用户输入变量制作二维数组?
- 一个变量的输入值也会保存到另一个变量中
- 如何在循环之外重新输入变量
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 使用单个变量对字符输入进行计数
- 如何在C++中从标准输入中获取变量输入
- 用户无法为第二个变量输入。C++
- C 错误:从命令行输入更改为变量输入
- 基于变量输入的泛型类方法计算
- 为什么我不能继续使用 std::cin 向同一变量输入其他值?
- 如何使用同一变量输入字母和数字?(C )
- C++:为什么为"int"变量输入"char"会导致递归变得疯狂?
- C++ 用户为整数变量输入非整数值
- 循环以丢弃来自stdin、Linux C++的虚假变量输入
- 如何通过cin为2个以上的变量输入流
- 为char类型变量输入多个字符的影响
- 接收从PHP到c++的各种变量输入
- 控制台应用程序-用户可以为c++中的整数变量输入的最高值是多少