[RESOLVED] *char user input
gragh! this should be simple! >.< I thought I had a good understanding of this by now.. guess I don't
basicly I want to do this:
Code:
char * name = "bob";
only have the user input it.
something like:
Code:
char * name;
cin >> name; //only this doesn't work
I must have tried a million different variations, different codes, jumping from different pointers, converting from strings, specifying specific char lengths, you name it, yet I either get an "not initialized" error (though isn't the cin initializing it? even so, even if I initialize it before the cin, I still get that error) or I get the pointer to the name the user entered, and the code I borrowed off someone else doesn't seem to take that because.. they seem they want the pointer to be the char, not a pointer to the char :s all I know is that the first example works beautifully, but as soon as I try to get the char from the user input it goes all poopy.
any help?
this should be simple in my head..
Re: [RESOLVED] *char user input
Hi P&P, that only works if you input contains no space
try this
char name[256];
cin.getline(name,strlen(name)+1);
Re: [RESOLVED] *char user input
Quote:
Originally Posted by
terminalXXX
Hi P&P, that only works if you input contains no space
try this
char name[256];
cin.getline(name,strlen(name)+1);
NO! name has not been initialised so no assumptions can be made about its content. strlen(name) returns the number of characters (unknown!) in the uninitialised char array. It is totally unpredictable how many characters can actually be input using this. It's possible that the char name array can overflow causing memory corruption problems.
If you really want to use char array (as opposed to c++ string) then the way to code this is:
Code:
const int MAX_INPUT = 255;
char name[MAX_INPUT + 1] = {0};
cin.getline(name, MAX_INPUT + 1);
It would be better to use c++ string and use
Code:
string uinp;
getline(cin, uinp);