[英]if my scanf variable is a float and a user inputs a character how can i prompt them to input a number? assuming the scanf is inside a do while loop
[英]How do i know if the input is an character or a float number with scanf?
我正在嘗試制作一個沒有任何錯誤的簡單計算器,但此外,每個示例,如果我輸入“a”,程序會有意外輸出。 基本上我的問題是當我輸入一個字符時,我可以為程序做些什么來顯示警告。 也許scanf
返回任何有用的值?
您可以簡單地使用 scanf 提供的標志來掃描整數。
int main()
{
float nb;
if (scanf("%f", &v) == 1) {
printf("Is float !\n");
} else {
printf("Not a float !\n");
}
return 0;
}
scanf 返回成功讀取的標志數,因此如果此數字不同於 1(在此示例中),則意味着 scanf 無法將您的輸入轉換為浮點數。
在添加的情況下:
int main()
{
float a;
float b;
if (scanf("%f +%f", &a, &b) == 2) {
printf("Result is %f\n", a + b);
} else {
printf("Error !\n");
return 1;
}
return 0;
}
這有效,但您必須編寫確切的 scanf 字符串。 我建議您將輸入行改為字符串,然后使用 strtol 或其他函數解析它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.