Thread: Easy question for you!

  1. #1
    Registered User
    Join Date
    May 2008

    Easy question for you!

    Hi guys, I'm trying to learn C++, and I'm just wondering what the deal is with this:

    #include <iostream>
    #include <string>
    int main()
    	std::string s;
    	std::cout << "Please enter a string: ";
    	std::cin >> s;
    	std::cout << "\nYou entered: " << s << "\n";
    The problem is when a user enters a string of more than 1 word, it'll only print the first. I.E say I enter "Hello there" it will say "You entered: Hello" instead of "You entered: Hello there". I'm guessing cin doesn't read whitespace or something, so I'm just wondering what is the way around this... Ok thanks!
    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

  2. #2
    Registered User
    Join Date
    Jan 2005
    It's the operator>> that stops at whitespace by default.

    If you're reading a string and you want a full sentence (up to when the user hits enter) then use getline:
    std::getline(std::cin, s);
    Don't forget to remove the call to std::cin.ignore(); since that only belongs there after calls to std::cin >>.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. easy Vector contructor question
    By noodle24 in forum C++ Programming
    Replies: 5
    Last Post: 04-21-2006, 07:43 PM
  2. Another Embarassingly Easy Question
    By almo89 in forum C Programming
    Replies: 2
    Last Post: 02-11-2006, 04:59 PM
  3. This is hopefully an extremely easy question...
    By rachaelvictoria in forum C Programming
    Replies: 2
    Last Post: 11-07-2005, 01:36 AM
  4. 4 easy question
    By Zeratulsdomain in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2005, 10:43 PM
  5. Easy Question
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 08-12-2002, 12:19 PM