-
Problems with cin.get()
Hi,
I'm trying to input the title of a movie from the user. Here's the code that's giving me trouble:
typedef char string [100];
string NewTitle;
cin.get(NewTitle);
I'm using MSVC++6 and it keeps giving me the error:
"error C2664: 'class istream &__thiscall istream::get(char &)' : cannot convert parameter 1 from 'char [100]' to 'char &'
A reference that is not to 'const' cannot be bound to a non-lvalue"
I was using plain old cin>>, but my program would freak out whenever I entered whitespace....
I'm pretty sure I've just screwed up the function syntax somehow, so if anyone can spot what I'm doing wrong, I'd appreciate it.
Thanks
-
std::cin.getline(NewTitle, 100);
try that.
edited for error, fixed now.
edit 2: cin.get() should work, but you need the same syntax as getline above.
-
>cin.get(NewTitle);
The one argument definition of get only accepts a single char, for an array you must also include the size as the second argument:
cin.get(NewTitle, 100);
-Prelude
-
new problem
Thanks! The error's gone. But, a new problem's popped up in it's place. I have a cin statement before the cin.get() that seems to be overriding the cin.get().
I'm not going to post all my program code (there's too much of it) so I just wrote a small test program that also has the same error in it:
int main()
{
typedef char string [100];
string NewTitle;
int SomeNumber;
cout<< "Enter a number: ";
cin >> SomeNumber;
cout << endl << SomeNumber << endl;
cout << "Enter a title: ";
cin.get(NewTitle, 100);
cout << endl;
cout << NewTitle << endl;
return 0;
}
When I run it I'll get output like this:
Enter a number: 3
3
Enter a title:
Press any key to continue
So as you can see, it looks like the cin.get() isn't being called at all; the program doesn't stop for input, I just entered "3" and it ended.
Any ideas on how to fix this so that it won't fast-forward all the way to the end, past the cin.get() ?
Thanks again
-
>Any ideas on how to fix this so that it won't fast-forward all the way to the end, past the cin.get() ?
cin's >> operator leaves a newline in the input stream, get stops reading at a newline. This tends to be a bad combination, one solution is to place
immediately after the first call to cin.
-Prelude
-
All better
Everything works now! Thanks, you've been a really big help.