Easy question for you!

This is a discussion on Easy question for you! within the C++ Programming forums, part of the General Programming Boards category; Hi guys, I'm trying to learn C++, and I'm just wondering what the deal is with this: Code: #include <iostream> ...

  1. #1
    Registered User
    Join Date
    May 2008
    Location
    Australia
    Posts
    230

    Easy question for you!

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

    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
    	std::string s;
    	std::cout << "Please enter a string: ";
    	std::cin >> s;
    	std::cin.ignore();
    	std::cout << "\nYou entered: " << s << "\n";
    	std::cin.get();
    }
    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
    Posts
    7,319
    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:
    Code:
    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, 03:59 PM
  3. This is hopefully an extremely easy question...
    By rachaelvictoria in forum C Programming
    Replies: 2
    Last Post: 11-07-2005, 12: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21