[英]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.