简体   繁体   中英

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. 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. 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. 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!

please Add "std::getchar()" to end of your code and try it again.

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM