My idea is storing “ANF23ie89Z” to array like arr[0] = ‘A’, arr[1] =
‘N’,… and sort them by bubble sort & ascii, and last print my input.
If you want to read one character at a time, each on a separate line, with scanf
, then you should use the %c
scanf directive (together with some means of consuming the newlines, which your getchar()
call provides), and loop once per character you want to read. Example:
char arr[20];
puts("Input 20 characters, one per line:");
for(int i = 0; i < 20; i++){
scanf("%c", &arr[i]);
getchar();
}
Do note that that is at risk to fall out of register if the user types any trailing characters on a line or any blank lines.
If you want to read all the characters on one line, and are prepared to assume that none are space or tab (or other whitespace) characters, then one scanf()
call with a %s
directive will accomplish it. Example:
char arr[21]; // <-- one byte is reserved for a string terminator
puts("Input 20 characters on one line, with no spaces or tabs:");
scanf("%20s", arr); // <-- field width prevents buffer overrun
int num_chars = strlen(arr); // <-- sort only this many characters
You have instead used a mishmash of the two. It might serendipitously work about as you expect for the one character per line case, but at minimum, it will overrun the bounds of your array by at least one byte in that case because you do not leave room for a string terminator after the 20th character.
But I got nothing in output.
That would be for a different, but related reason: your arr[i]
is one character, not a string. When you tell printf
to interpret it as a string via the %s
directive, you elicit undefined behavior, which is extremely unlikely to be printing the value as if it were a character. I'm surprised that the program does not fail with your system's flavor of memory-access fault. Or does it? That would have been relevant information to include in the question.
In any case, the situation on output is analogous to the one on input: either print characters, one at a time, with %c
, or print a whole string, all at once, with %s
(or other, similar variations). In the latter case, you must actually have a string, meaning that the data are terminated by a null character. Examples:
// one character at a time, each on its own line
for(int i = 0; i < 20; i++){
printf("%c\n", arr[i]);
}
/* OR */
// all characters on the same line, assuming arr contains a string
printf("%s\n", arr);
Note also: if you decide to go the string route, be sure to exclude the terminator from your sort. It needs to stay at the end of the string, else the effect will be a logical truncation of the string -- probably to an empty string.