[英]scanf read variable number of characters
我想知道如果按回車鍵,如何使scanf
跳過閱讀字符...我的代碼如下:
#include <stdio.h>
int main(void)
{
int a, status;
char b;
printf("Please enter a positive number immediately"
"followed by at most one lower-case letter:\n\n");
status = scanf("%i%c", &a, &b);
if (status == 1 && getchar() == '\n') {
printf("\nThank you!\n");
}
return 0;
}
當我只輸入數字而沒有其他輸入時,我需要再次按Enter來觸發scanf
的%c
&b
。 如何避免這種情況並使程序僅接受1個數字以跳轉到printf
?
我試過了:
if (status == 1 && getchar() == '\n')
但這行不通。
如評論中所述,最佳做法是使用fgets
讀取字符串,然后對其進行解析和驗證。 該線程將為您提供足夠的資源,以使您了解fgets
的用法。
這是您可以采用的一種方法。 請注意,此代碼不會嘗試驗證用戶可以提供的所有可能的輸入,而是為您提供一個合理的指導,如果您認為輸入正確,則可以采取解決問題的方法。 我將把驗證任務留給您。 下面的代碼應提供足夠的工具來完成其余任務。 查看使用for
循環單步執行buffer
並確保輸入正確。 使用isalpha()
和isdigit()
測試每個字符。 您也可以實現自己的功能以測試每個字符
在這個答案中 。
#include <stdio.h>
#include <stdlib.h> //for atoi()
#include <string.h> //for strlen()
#include <ctype.h> //for isalpha()
#define MAX_INPUTLENGTH 500
int main(void)
{
//Always a good idea to initialize variables to avoid Undefined Behaviour!
char buffer[MAX_INPUTLENGTH] = { '\0' };
int a = 0, status = 1, length = 0;
char b = '\0';
printf("Please enter a positive number immediately"
"followed by at most one lower-case letter:\n\n");
//this gets you a string you can work with
fgets(buffer, sizeof(buffer), stdin);
length = strlen(buffer);
buffer[length - 1] = '\0';//remove the trailing '\n'
length--;
//now see if last character is a letter
if (isalpha(buffer[length - 1])) {
b = buffer[length - 1];//then assign and..
buffer[length - 1] = '\0';//trim the letter
}
//this function converts the remaining string to an int
a = atoi(buffer);
//Use the debugger and observe how these functions work in order
//to validate the input. for now, status is always 1!
if (status == 1) {
printf("\nThank you!\n");
}
return 0;
}
正如@Jonathan在下面的注釋中指出的那樣,要可移植地獲取數組的計數,應使用sizeof(buffer) / sizeof(buffer[0])
。 由於您使用的是char[]
,因此sizeof(buffer[0])
值為1
,因此在調用fgets
時可以將其省略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.