[英]Printing a string backwards in C with scanf
我試圖在c中向后打印我的字符串,但似乎無法使其與空白一起使用。 我知道,在scanf函數中最后一個返回的字符之后如果有空格,它將終止,因為沒有剩余的字符可從輸入的字符串中進行掃描。 這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLETTERS 20
void readStringBackwards();
main()
{
readStringBackwards();
}
void readStringBackwards()
{
printf("Please enter a string of up to 20 characters in length:\n ");
char str[20];
scanf("%s", str);
int i;
int stringlength = strlen(str);
if (stringlength > MAXLETTERS)
{
printf("The string length is too long!");
}
else
{
for( i = stringlength-1; i >= 0; i--){
printf("%c ", str[i]);
}
}
}
本質上,程序應該接受最多20個字符,並向后打印字符串。 我一直在尋找有關scanf及其工作方式的信息,但是很難找到直接的答案。 任何提示表示贊賞。 現在,我所得到的只是我反向輸入的第一個單詞。 空格后的其他字符將被跳過,並且不會存儲在數組中。
為什么不使用fgets()
而不是scanf()
呢?
char str[21]; // Note 21, not 20 (remember the null terminator)
fgets(stdin, 21, str);
請注意,如果字符串少於20個字符,則會包含換行符,因此您需要刪除該字符(用'\\0'
覆蓋是可以的)。
scanf("%s", str);
將讀取一個空格,即使其超過20個字符。 空白,換行和制表符被視為空白字符。
考慮使用諸如"%20[^\\n]"
類的格式規范,只要不是'\\n'
,就最多可以讀取20個字符。
編輯:正如奧利·查爾斯沃思(Oli Charlesworth)所指出的那樣,緩沖區必須至少為21,而不是20。
這段代碼可以正常工作,但是嘗試使用gets()
而不是scanf()
來讀取字符串中的空格!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.