Reputation: 655
char ch[4];
char* ptr;
ptr = ch;
while(1)
{
cin >> *ptr;
if(*ptr == '\n')
break;
ptr++;
}
Here I just wrote a bit of sample code where I am trying to get out of a while loop when user writes ENTER but it's not working. Please help me. Thank you in advance.
Upvotes: 0
Views: 764
Reputation: 21
The extraction operator would skip leading white-spaces and stop execution on encountering any subsequent white-space. So, when you want to do something like this, use std::istream::get() or std::istream::getline().
Upvotes: 1
Reputation: 657
The following will read a line:
istream& getline (char* s, streamsize n );
Upvotes: 1
Reputation: 6776
You are reading input into the value of a character. That's what *ptr
means. I think you want just plain ptr, which is a pointer to an array of characters, which is something that is meant to receive data. What you wrote is basically this:
char c;
cin >> c;
I don't think that's what you meant, nor would it work even if it were, since as Joachim Pileborg points out above, the >>
operator skips whitespace like newlines. In general, it is always best to be very robust when it comes to reading input. Provide adequate space, and either use a variable that can grow automatically (like std::string
) or tell the system how much space you have (like fgets()
).
Upvotes: 1
Reputation: 409136
To get a single character, use std::istream::get
. This should work for getting newlines as well.
But instead of getting characters in a loop until you get a newline, why not just use something like std::getline
:
std::string str;
std::getline(cin, str);
Or if you only want to get max three characters you can use std::istream::getline
:
char ch[4];
cin.getline(ch, 4, '\n');
Upvotes: 6