[英]Why does my C program print new blank lines when I try to print a string in the reverse order?
我正在尝试制作一个程序,该程序以相反的顺序返回带有元素的数字和字符串。 我都能做到,但我不明白为什么在打印反转字符串时为什么会有一些空白的新行
我也使用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 est但是实际输出是:
测试
从fgets的手册页
fgets()
最多从流中读取小于大小的字符,并将它们存储到s所指向的buffer
。 在EOF
或newline
之后停止读取。 如果读取了newline
,则将其存储在buffer中 。 所以在这里
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 */
textLen
是字符串s
的字符数。 打印的第一个字符是s[textLen]
,它是末尾的NUL字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.