std::cin input with spaces?

前端 未结 8 1207
再見小時候
再見小時候 2020-11-21 05:41
#include 

std::string input;
std::cin >> input;

The user wants to enter \"Hello World\". But cin fails at the spa

8条回答
  •  走了就别回头了
    2020-11-21 06:22

    How do I read a string from input?

    You can read a single, whitespace terminated word with std::cin like this:

    #include
    #include
    using namespace std;
    
    int main()
    {
        cout << "Please enter a word:\n";
    
        string s;
        cin>>s;
    
        cout << "You entered " << s << '\n';
    }
    

    Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow. If you really need a whole line (and not just a single word) you can do this:

    #include
    #include
    using namespace std;
    
    int main()
    {
        cout << "Please enter a line:\n";
    
        string s;
        getline(cin,s);
    
        cout << "You entered " << s << '\n';
    }
    

提交回复
热议问题