我有以下代码:
int main()
{
// Variables
char name;
// Take the users name as input
cout << "Please enter you name..." << endl;
cin >> name;
// Write "Hello, world!" and await user response
cout << "Hello, " << name << "!" << endl;
cout << "Please press [ENTER] to continue...";
cin.get();
return 0;
}
用户按下回车键输入姓名后,回车符会被转到代码末尾,并立即作为 cin.get() 的输入,从而提前结束程序。我可以在接下来的行中放置什么内容
cin >> name;
阻止这种情况发生?我知道这是可能的,因为我以前做过,但不记得它是什么或在哪里可以找到它。预先非常感谢。
实际上,您想使用输入中直到换行符的所有内容作为名称。
目前您的代码仅读取第一个单词。
#include <iostream>
#include <string>
int main()
{
// Variables
std::string name;
// Take the users name as input
// Read everything upto the newline as the name.
std::cout << "Please enter you name..." << std::endl;
std::getline(std::cin, name);
// Write "Hello, world!" and await user response
// Ignroe all input until we see a newline.
std::cout << "Hello, " << name << "!\n";
std::cout << "Please press [ENTER] to continue..." << std::flush;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)