Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,233 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,799 people online right now. Registration is fast and FREE... Join Now!




cin

 
Reply to this topicStart new topic

cin

pietra
15 Mar, 2007 - 09:09 AM
Post #1

D.I.C Head
**

Joined: 8 Feb, 2007
Posts: 70


My Contributions
*sighs* sorry to bother you but for some reason I can't get cin to work properly.

I have this code

CODE

#include <iostream>
#include <string>

int main ()
{
    
    string str;
    std::cout << "enter name: " << std::endl;
    std::cin >> str;    
    std::cout << "hello, " << str << std::endl;
    getchar();
    return 0;
}


And "enter name" is printed, as soon as I type something (text) and press enter program finishes.

if I change std::cin >> str; with getline(cin, str); it's working. I think it's trivial mistake, but I don't get it, huh.gif
User is offlineProfile CardPM
+Quote Post

Amadeus
RE: Cin
15 Mar, 2007 - 09:19 AM
Post #2

g++ -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 12,230



Thanked: 40 times
Dream Kudos: 25
My Contributions
It's not a mistake, so no worries there.

1. the cin >> stream operator only takes up to the first whitespace.
2. Even if the input is one word, the cin stream operator does NOT take the newline character (inserted by the return key) into the variable. this means that the newline character is still in the stream. when you call getchar(), it takes that newline character from the stream, as it's the first thing sitting there.

The getline() function takes the newline character as well.

You can either use getline(), clear the stream after the first input, or use two calls to getchar() (or one of the other character retrieval methods).
User is online!Profile CardPM
+Quote Post

pietra
RE: Cin
15 Mar, 2007 - 09:33 AM
Post #3

D.I.C Head
**

Joined: 8 Feb, 2007
Posts: 70


My Contributions
I knew you're gonna answer Amadeus and help me, thank you smile.gif

If I continue like this and you keep helping me out I'll have to take you to lunch some day cool.gif
User is offlineProfile CardPM
+Quote Post

Amadeus
RE: Cin
15 Mar, 2007 - 09:36 AM
Post #4

g++ -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 12,230



Thanked: 40 times
Dream Kudos: 25
My Contributions
Hahahaha...no worries! smile.gif
User is online!Profile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/4/08 03:33PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month