Tuesday, July 28, 2009

C++ Using char* instead of getline(cin, aString)?

How do you use a char* instead of using getline(cin, aString)?

C++ Using char* instead of getline(cin, aString)?
OopsIDied is mostly correct. If you use char * you must allocate space for it, either by declaring it as an array or by using new, in which case you had better use delete.





The thing is, if you use the %26gt;%26gt; operator what will happen is what will happen with the C scanf("%s",%26amp;variable) function: the first whitespace character it gets will terminate the string. It could be a tab or a space or a newline. Whatever it is, the next char written to your array will be a null terminator for your ASCIIZ string. Either use cin.getline(aString) or the C function gets(String) unless you don't want any whitespace.
Reply:char* VariableChar;


cin %26gt;%26gt; VariableChar;





Note that char* has enough space for one letter, any more might crash your program. You can try a buffer instead.





char VariableChar[256];


cin %26gt;%26gt; VariableChar;





That would have space for 256 characters.





You can use exceptions to handle times when the user puts too many letters, but that's outside the scope of this question...

apple

No comments:

Post a Comment