为什么scanf()在这个程序中忽略空格后面的部分来反转字符串?

bkkx9g8r  于 2023-08-03  发布在  其他
关注(0)|答案(2)|浏览(95)
#include <stdio.h>

#include <string.h>

main() {
    int i;
    char given[30];
    char reversed[30];
    printf("enter your stringn");
    scanf("%s", given);
    for (i = 0; i <= (strlen(given)); i++) {
        if (i <= (strlen(given) - 1)) {
            reversed[i] = given[(strlen(given) - 1 - i)];
        } else {
            reversed[i] = given[i];
        }
    }
    printf("%s", reversed);
    return 0;
}

字符串
当我运行这段代码时,如果我给予输入作为123,它将返回321,但当我将123 325作为输入时,它将只给出321作为输出(它应该是523 321)。为什么会这样呢?

huus2vyu

huus2vyu1#

对于初学者,函数main应该显式指定返回类型int(或兼容)

int main( void )

字符串
至于你的问题那么根据C标准(7.21.6.2 fscanf函数;这同样适用于scanf
s匹配一个非空白字符序列。
也就是说,一旦遇到白色字符,就停止填充用作参数表达式的相应字符数组。非白色字符的读取序列以空字符'\0'结束。因此,只有来自用户输入的第一个单词123被程序读取和反转,如果你有一个循环,输入行的其余部分将由另一个对scanf()的调用读取。
如果要读取包含白色字符的字符串,则需要使用另一种转换规范,例如:

scanf(" %29[^\n]", given);


还要注意,多次调用函数strlen是低效的。
你也应该在使用变量的最小范围内声明变量。
您的程序可以看起来像下面这样

#include <stdio.h>
#include <string.h>

int main( void ) 
{
    char given[30];
    char reversed[30];

    printf( "enter your string: " );
    
    if ( scanf(" %29[^\n]", given) == 1 )
    {
        size_t n = strlen( given );
        reversed[n] = '\0';

        for ( size_t i = 0; i < n; i++ ) 
        {
            reversed[i] = given[n - 1 - i];
        }

        puts( reversed );
    }

    return 0;
}

ecfsfe2w

ecfsfe2w2#

%s不会读取整行。看看here%s的条目表示为Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
也许How do you allow spaces to be entered using scanf?How to read one whole line from a text file using < ?可以为您提供替代方案。

相关问题