我試圖讓這個代碼來驗證用戶輸入的值。它工作,如果我使用gets(),但當我改變它fgets()它停止工作。我希望它保持循環,直到用戶輸入一個至少包含1個字符但小於25的字符串。如果在我的代碼中不明顯,我是編程新手。謝謝!如何確保用戶輸入一個值?
int main(void)
{
char input[25], inputNew[25];
int i;
int x;
int y;
do
{
printf("Please enter a string less then 25 characters!\n");
fgets(input, sizeof(input), stdin);
y = strlen(input);
}
while(y>25 || y<=0);
for (i = 0; i <= strlen(input); i++)
{
inputNew[i] = toupper(input[i]);
for (x = 1; x <= strlen(input); x+=2)
{
inputNew[x] = tolower(input[x]);
}
}
printf("The new value is: %s.\n", inputNew);
return 0;
}
你可以使用'getline',有你'input'是'malloc'-ED指針。 –
...如果你願意去glibc只。 – nneonneo
將字符輸入[25]的變量大小更改爲大於25的值。檢查此答案(http://stackoverflow.com/a/12907742/937420) – Antarus