简体   繁体   中英

Printing a string backwards in C with scanf

I am trying to print my string backwards in c and I just can't seem to get it working with whitespaces. I am aware that if there is any whitespace after the last returned character in the scanf function that it will terminate because there is no existing characters left to scan in from the string entered. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLETTERS 20

void readStringBackwards();

main()
{
readStringBackwards();
}


void readStringBackwards()
{



printf("Please enter a string of up to 20 characters in length:\n ");
char str[20];
scanf("%s", str);
int i;
int stringlength = strlen(str);

if (stringlength > MAXLETTERS)
{
    printf("The string length is too long!");
}
else
{
    for( i = stringlength-1; i >= 0; i--){

        printf("%c ", str[i]);

    }

}



}

Essentially the program is supposed to accept up to 20 characters, and print the string backwards. I have been searching for information on scanf and how it works, but its been pretty hard to find a direct answer. Any tips are appreciated. Right now all I will get is the first word that I type in reverse. The other characters after an space are skipped and not stored within the array.

Why not use fgets() instead of scanf() ?

char str[21]; // Note 21, not 20 (remember the null terminator)
fgets(stdin, 21, str);

Note that if the string is less than 20 characters, you'll get the newline character included, so you'll need to remove that (overwriting with '\\0' is fine).

scanf("%s", str); will read up to a whitespace, even if its more than 20 chars. Blank, newline and tab are considered whitespace characters.

Consider using a format specification like "%20[^\\n]" , that should be read up to 20 chars as long as they are not '\\n' .

edit: As Oli Charlesworth pointed out, the buffer would have to be at least length 21, not 20.

这段代码可以正常工作,但是尝试使用gets()而不是scanf()来读取字符串中的空格!

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