在C ++中使用std :: getline()输入带有空格的输入

时间:2019-11-27 19:59:41

标签: c++

我对使用C ++进行编码非常陌生,并且正在MAC上使用Visual Studio Code。我试图找到正确的代码,以便可以输入带空格的字符串,但是我尝试的所有方法均无效。我尝试了std::getline(std::cin, name),但是当我运行代码时,是时候输入名称了,它什么也没显示。我不知道Visual Studio代码是否有问题,或者我缺少的只是一点点代码。这是我遇到问题的代码。

#include <iostream>
#include <string>
#include <cmath>
#include <sstream>
#include <string.h>

int main (){

std::string name;

std::cout << "Please, enter the name of your nation: ";
std::getline(std::cin, name);
std::cout << "General Williams: " << name << " is a great name!\n";
}

1 个答案:

答案 0 :(得分:0)

我执行了您的代码,它成功了。 也许因为运行.exe而看不到结果!

请在代码末尾添加“ std :: getchar()”,然后重试。

int main()
{
        std::string name;

        std::cout << "Please, enter the name of your nation: ";
        std::getline(std::cin, name);
        std::cout << "General Williams: " << name << " is a great name!\n";
        std::getchar();

}