我有以下代码:
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;
阻止这种情况发生?我知道这是可能的,正如我之前所做的那样,但是不记得它是什么或者我在哪里可以找到它。非常感谢。
答案 0 :(得分:7)
你真的想要使用输入上的所有内容作为名称 目前,您的代码只读取第一个单词。
#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')
}
答案 1 :(得分:4)
最简单的答案:
int main()
{
// Variables
char name;
// Take the users name as input
cout << "Please enter you name..." << endl;
cin >> name;
cin.get(); // get return here
// Write "Hello, world!" and await user response
cout << "Hello, " << name << "!" << endl;
cout << "Please press [ENTER] to continue...";
cin.get();
return 0;
}
答案 2 :(得分:3)
您可以告诉您的信息流忽略
中的下N个字符cin.ignore(1000, '\n');
这会导致cin
最多跳过1000个字符或直到找到(并删除)换行符('\n'
)。其他限制或终止字符可以根据需要指定。
答案 3 :(得分:1)
cin
忽略回车符,'\n'
之前的值存储在变量中,'\n'
保留在输入流中。调用cin.get()
时,它会获取输入流中已有的值(即'\n'
),因此会跳过它。
为了避免这种情况,蒂姆的答案是完美的!
cin >> name;
cin.get(); // get return here
或者您也可以
(cin >> name).get(); // get return as soon as cin is completed.
更新:正如Loki Astari所指出的,当使用cin>>
运算符到数组name
时,它会读取第一个空格字符。在'Tim Hoolihan'中,名字之间有一个空格。因此,name数组将{'T','i','m','\n'}
存储为值,'\n'
标记字符串的结尾。应该避免对字符串使用char数组,而是使用string
头文件中的类#include<string>
。字符串之间可以包含空格字符,而数组则不能。
#include<iostream>
#include<string>
int main()
{
string name; // string is a class, name is the object
cout << "Please enter you name..." << endl;
(cin >> name).get();
cout << "Hello, " << name << "!" << endl;
// String using the "power" of an array
cout << "First two characters of your name are " << name[0] << name[1] << endl;
cout << "Please press [ENTER] to continue...";
cin.get();
return 0;
}
答案 4 :(得分:0)
首先,名称是一个字符串,您正在char
中阅读。
char name;
应该是
string name;
同时添加#include<string>
现在从缓冲区中清除换行符:
std::cin.ignore(1);
阅读name
。