开发者

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 s开发者_JAVA百科tring 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.


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.


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).


This code is working perfectly but try using gets() instead of scanf() to read spaces in string!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜