c - 为什么这个反向字符串程序不起作用?

标签 c

我是 C 编程新手,所以请原谅我的天真。以下程序在输出时无法将输入字符串的最后一个字符打印为输出字符串的第一个字符。

例如:

Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh

为什么o不打印?

#include <stdio.h>

int main() {
    printf("Enter no. of elements: ");
    int n;
    scanf("%d", &n);
    char string[10000];
    printf("Enter string: ");
    for (int i = 0; i < n; i++) {
        scanf("%c", &string[i]);
    }
    printf("The reversed string is: ");
    for (int i = (n - 1); i >= 0; i--) {
        printf("%c", string[i]);
    }
    printf("\n");
    return 0;
}

最佳答案

您要注意一个副作用:

  • scanf("%d", &n);之后,输入流缓冲区中有一个挂起的换行符。

  • 当您稍后输入 n 个字符时,scanf("%c", &string[i]) 首先读取挂起的换行符,然后 n-1 您输入的第一个字符,输入的其余部分保留在输入缓冲区中。

scanf() 是一个非常笨重的函数。很难正确使用。

这是解决您的问题的方法:

#include <stdio.h>

int main() {
    char string[10000];
    int i, n, c;

    printf("Enter no. of elements: ");
    if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
        return 1;

    // read and discard pending input
    while ((c = getchar()) != '\n' && c != EOF)
        continue;

    printf("Enter string: ");
    for (i = 0; i < n; i++) {
        if (scanf("%c", &string[i]) != 1)
            break;
    }
    // the above loop could be replaced with a single call to fread:
    // i = fread(string, 1, n, stdin);

    printf("The reversed string is: ");
    while (i-- > 0) {
        printf("%c", string[i]);
    }
    printf("\n");
    return 0;
}

关于c - 为什么这个反向字符串程序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45268877/

相关文章:

c - 二维数组 - C 中的无效初始值设定项?

c - 慢慢出现printf,在C99中

c++ - c表达式和c++表达式的区别

c - 消息目录文件的默认扩展名

将非 GUI Makefile (make) 项目转换为 KDevelop

c - 数组大小说明

c - 等待来自文件描述符的输入

c - 为什么在我尝试释放矩阵时显示错误?

c - 如何在不使用 C 语言中的整数类型的情况下将 2 uint8 模乘一个大数

c - 发送 i2c 消息时 ioctl() 调用中的 valgrind 错误