我正在尝试制作一个程序,该程序返回一个数字和一个字符串,其中元素的顺序相反。我能够做到这两点,但我不明白为什么当我打印出反转的字符串时会有一些空白的新行
我也试过用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 thebuffer
pointed to by s. Reading stops after anEOF
or anewline
. If anewline
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/