Question:
Error with 'cin' in C++ when user input too long.?
robing
2008-12-10 09:18:01 UTC
I am a beginner to C++ and am writing some basic console applications. My program accepts input from the user into a character array like so:

char answer[80];
cin >> answer;

This causes a problem if the user enters too much data. If I try it with an unsized array like so:

char answer[];
cin >> answer;

the compiler returns an error. What should I do so that the user can enter as much data as they like without causing an error?

Thanks for all your help.
Three answers:
Matt Flaschen
2008-12-10 09:27:08 UTC
Use a C++ string instead of character array. It will handle the allocation for you:



See http://www.cplusplus.com/reference/string/getline.html . There is no such thing as an "unsized array" (there are 0-length arrays but that won't help either).



Alternatively, if you want to use character arrays, you can use GNU getline (http://www.gnu.org/software/libtool/manual/libc/Line-Input.html) if you're on a GNU (or some other UNIX) system.



char *answer = NULL;

int count = 0;

getline(&answer, &count, stdin);



answer is a character pointer. If you aren't familiar, it's similar to an array for most purposes.



If you do it the second way, you must call:



free(answer);



when you're done with the answer variable.
Drew M
2008-12-10 09:29:37 UTC
std::cin is of type std::istream, so you have access to all the methods associated with that class. One possibility is that instead of using the >> operator, you could do the following:



char answer[80];



cin.getline(answer, 80 - 1); // less one character for the NULL character that signifies the end of the string.



Check out the standard iostream library in the reference below for more details.
?
2016-12-24 20:49:52 UTC
i might advise using strtok to cut up up the line on the delimiter of ",". Then examine that it replaced into chop up into 10 substrings, and that there is a era on the tip of the final one. Then pass by each and each substring and consider that that is under 10 characters long. i'm undecided of syntax, even though it would no longer be too confusing to locate a demo that does something comparable. the positioning under can get you began. additionally, i might advise changing the instant and mistake message to assert "(10 characters each and each optimal)", as i presumed on the beginning up you meant they had to apply finest areas and stuff to make each and each interest precisely 10 characters.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...