用C++清除内存中的回车符

4 c++

我有以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

}

在用户命中返回以输入其名称之后,该回车被转发到代码的末尾,其中它立即被应用为cin.get()的输入,从而过早地结束程序.我可以立即在线上放置什么

cin >> name;
Run Code Online (Sandbox Code Playgroud)

阻止这种情况发生?我知道这是可能的,正如我之前所做的那样,但是不记得它是什么或者我在哪里可以找到它.非常感谢提前.

Mar*_*ork 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')
}
Run Code Online (Sandbox Code Playgroud)