c - 当我尝试以相反顺序打印字符串时,为什么我的 C 程序会打印新的空白行?

标签 c string

我正在尝试制作一个程序,该程序返回一个数字和一个字符串,其中元素的顺序相反。我能够做到这两点,但我不明白为什么当我打印出反转的字符串时会有一些空白的新行

我也试过用scanf函数只用一个单词,还是出现空行

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char s[50];
   int i, n, lastDigit, textLen=0;

   printf("Enter a number: ");
   scanf("%i", &n);
   getchar();

   printf("Enter the text: ");
   fgets(s, 50, stdin);

   printf("The reversed number is: ");

   while(n > 0){
    lastDigit = n%10;
    n=n/10;
    printf("\n%i", lastDigit);
   }

    printf("\nThe reversed text is: ");

     while(s[textLen] != '\0'){
        textLen++;
    }

   for(i=textLen; i>=0; i--){
    printf("\n%c", s[i]);
   }

return 0;
}

我希望: 吨 电子 秒 吨 但实际输出是:

T 电子 秒

最佳答案

来自 fgets 的手册页

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. So here

char s[50];
fgets(s, 50, stdin);

fgets()换行符 存储在缓冲区 s 的末尾(如果已读取)。要删除尾随的 \n 字符,请使用 strcspn()。例如

char s[50] = {}; /* Initialize it */
fgets(s, 50, stdin); 
s[strcspn(s, "\n")] = 0; /* remove the trailing \n */

关于c - 当我尝试以相反顺序打印字符串时,为什么我的 C 程序会打印新的空白行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56306859/

相关文章:

ruby - 如何使用 Ruby 匹配较长字符串中以 'H' 开头的 10 个字符的子字符串?

c - 对二维数组每行的所有最大元素求和

c - 使用系统调用读取 "space"[在 Unix 中使用 C]

java - 三元运算符的奇怪行为

java - 从一个文件中获取整数列表

python - 在同一行中创建多个 "char*"变量时出现无效类型错误

c - 如何将结构体数组复制到同一数组中的另一个结构体?

c - AT89S52中使用C代码的中断

c - 将宏标记为已弃用的最佳方法是什么?

php - 将反斜杠分隔的字符串转换为关联数组