简体   繁体   English

我在 cin.get() 中遗漏了什么吗?

[英]Am I missing something with cin.get()?

I'm learning cin.get() in C++ and I'm trying to echo two chars (including whitespace) back to the user.我正在学习 C++ 中的cin.get()并且我试图将两个字符(包括空格)回显给用户。

While running the code, it doesn't echo out the inputs properly.在运行代码时,它不会正确地回显输入。

char letter1, letter2;

cout << "Enter Letters: ";
cin >> letter1 >> letter2;
cin.get(letter1);
cin.get(letter2);
cout << "letter1 is: " << letter1 << " end.\n";
cout << "letter2 is: " << letter2 << " end.\n";

I intend to input 2 and 3, however, it gives me a different result:我打算输入 2 和 3,但是,它给了我不同的结果:

Input (I had to type 3 twice for some reason)输入(由于某种原因,我不得不输入 3 两次)

Enter  Letters:2
3
3

Output输出

letter1 is:
end.
letter2 is: 3 end.

The formatted input operators skip leading whitespace (unless doing so is explicitly disabled, eg, using in >> std::noskipws; ).格式化输入操作符跳过前导空格(除非这样做被明确禁用,例如,使用in >> std::noskipws; )。 The unformatted input functions do not skip leading whitespace.未格式化的输入函数不会跳过前导空格。 As a result, the first use of std::cin.get(letter1) reads the newline character and the second use reads the entered digit.结果,第一次使用std::cin.get(letter1)读取换行符,第二次使用读取输入的数字。

You can explicitly skip leading whitespace, eg:您可以明确跳过前导空格,例如:

if ((std::cin >> std::ws).get(letter1)) {
    std::cout << “read ‘“ << letter1 << “‘\n”;
else {
    std::cout << “failed to read a character\n”;
}

The example also added some basic error handling: input should always be expected to fail and failures need to be handled appropriately.该示例还添加了一些基本的错误处理:应始终预期输入会失败,并且需要适当处理失败。 Obviously, failures need to be checked after the attempt to read input.显然,在尝试读取输入需要检查故障。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM