[英]Taking in input with spaces using std::getline() in c++
I am pretty new to coding in c++, and I am using Visual Studio Code on MAC. 我对使用C ++进行编码非常陌生,并且正在MAC上使用Visual Studio Code。 I have tried to find the right code so that I can enter a string with spaces, but everything that I tried hasn't worked. 我试图找到正确的代码,以便可以输入带空格的字符串,但是我尝试的所有方法均无效。 I tried std::getline(std::cin, name)
, but when I ran the code, and it came time to input the name, it just showed nothing where the name should have been. 我尝试了std::getline(std::cin, name)
,但是当我运行代码时,是时候输入名称了,它什么也没显示。 I don't know if there is something wrong with Visual Studio Code, or if there is just a little bit of code that I am missing. 我不知道Visual Studio代码是否有问题,或者我缺少的只是一点点代码。 Here is the code that I am having a problem with. 这是我遇到问题的代码。
#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";
}
I executed your code and it worked. 我执行了您的代码,它起作用了。 Maybe you can not see your result because you run with .exe! 可能因为使用.exe运行而看不到结果!
please Add "std::getchar()" to end of your code and try it again. 请在代码末尾添加“ 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.