What are the rules of the std::cin object in C++?

前端 未结 2 1212
情话喂你
情话喂你 2021-01-16 13:25

I am writing a small program for my personal use to practice learning C++ and for its functionality, an MLA citation generator (I\'m writing a large paper with tens of citat

相关标签:
2条回答
  • 2021-01-16 14:02

    What is happening here is that std::cin >> firstName; only reads up to but not including the first whitespace character, which includes the newline (or '\n') when you press enter, so when it gets to getline(std::cin, articleTitle);, '\n' is still the next character in std::cin, and getline() returns immediately.

    // cin = "Bloggs\nJoe\nMan of Steel, Woman of Kleenex\n"
    std::cin >> lastName;
    std::cin >> firstName;
    // firstName = "Joe", lastName = "Bloggs", cin = "\nMan of Steel, Woman of Kleenex\n"
    getline(std::cin, articleTitle);
    // articleTitle = "", cin = "Man of Steel, Woman of Kleenex\n"
    

    Adding 'std::cin >> std::ws' (ws meaning whitespace) before your calls to getline() fixes the problem:

    std::cin >> firstName >> std::ws;
    getline(std::cin, articleTitle);
    

    But it is easier to see where you missed it if you do it in the argument:

    std::cin >> firstName;
    getline(std::cin >> std::ws, articleTitle);
    
    0 讨论(0)
  • 2021-01-16 14:23

    When you use the >> operator, cin reads up until the next whitespace character, but it doesn't process the whitespace. So when you have

    std::cin >> str1;
    std::getline(std::cin, str2);
    

    the second call will just process the newline character, and you won't have a chance to type in any input.

    Instead, if you're planning to use getline after an operator >>, you can call std::cin.ignore() to eat the newline before you call getline.

    Edit: it works as you expected when you do

    std::cin >> str1;
    std::cin >> str2;
    

    since the second call will ignore all leading whitespace.

    0 讨论(0)
提交回复
热议问题