简体   繁体   English

使用scanf在C中向后打印字符串

[英]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. 我试图在c中向后打印我的字符串,但似乎无法使其与空白一起使用。 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. 我知道,在scanf函数中最后一个返回的字符之后如果有空格,它将终止,因为没有剩余的字符可从输入的字符串中进行扫描。 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. 本质上,程序应该接受最多20个字符,并向后打印字符串。 I have been searching for information on scanf and how it works, but its been pretty hard to find a direct answer. 我一直在寻找有关scanf及其工作方式的信息,但是很难找到直接的答案。 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() ? 为什么不使用fgets()而不是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). 请注意,如果字符串少于20个字符,则会包含换行符,因此您需要删除该字符(用'\\0'覆盖是可以的)。

scanf("%s", str); will read up to a whitespace, even if its more than 20 chars. 将读取一个空格,即使其超过20个字符。 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' . 考虑使用诸如"%20[^\\n]"类的格式规范,只要不是'\\n' ,就最多可以读取20个字符。

edit: As Oli Charlesworth pointed out, the buffer would have to be at least length 21, not 20. 编辑:正如奥利·查尔斯沃思(Oli Charlesworth)所指出的那样,缓冲区必须至少为21,而不是20。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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