简体   繁体   中英

How to store user input of one character into EACH element of an array in C++?

I want the user to input just one character, say 'Y', then I want Y to be stored in each element of an array (ie: array[9]) so that when I print it would be like 'YYYYYYYYY', or when it's a 2d array (ie: array[2][2]) it would look like:

YYY
YYY
YYY   

If you need to print each entered character same number of times, why to store all? it will waste memory, just store one character and it print any number of times needed, so a single array will be enough,i guess. But this solution is what i got from your question, if there are some constraints please do share or better share code...

You can use memset() from <cstring> , or std::fill() from <algorithm> . So for a char array[9]; , you can do:

memset(array, 'Y', 9);

or:

std::fill(array, array + 9, 'Y');

For a 2D array, you'd set each row individually.

Watch out when using memset(), because the length is given in bytes, not in elements. If you had an int array, for example, memset(array, 'Y', 9) wouldn't work. std::fill() does not have that problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM