[英]Counting Number Of User Input in C Program
printf("Enter number of patients:");
int numberOfInputs = scanf("%d", &patients);
if (numberOfInputs != 1) {
printf("ERROR: Wrong number of arguments. Please enter one argument d.\n");
}
我要求用戶輸入一個數字作為參數,但如果用戶沒有輸入任何內容或輸入多個輸入,我想打印出一個語句。 例如,一旦提示“輸入患者數量:”,如果用戶沒有輸入任何內容就點擊回車,我想打印出一個語句。 上面的代碼是我在過去幾個小時里一直在專門修補它的內容,正如本網站上的一些以前的帖子所建議的那樣,但是當我在終端中運行它時,它不起作用。 有什么建議? 在此先感謝您,非常感謝所有建議!
如果我理解你的問題,當輸入不是整數時,你想打印一個錯誤,這也包括換行符。 您可以使用char
數組和%[]
說明符來做到這一點。
例子:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int patients;
char str[10];
printf("Enter number of patients:");
int numberOfInputs = scanf("%[0-9]", str);
if (numberOfInputs != 1) {
printf("ERROR: Wrong number of arguments. Please enter one argument.\n");
}
patients = atoi(str); //This is needed to convert the `str` back to an integer
}
這也將在用戶按 ENTER 時打印錯誤。
這看起來非常復雜,但它基本上拆分了輸入,檢查它是否恰好為 1,然后檢查它是否為整數(並對其進行轉換)。 它在循環中也能正常工作並處理空輸入。 我相信這個問題有更優雅的解決方案,這只是一個建議。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
int getNumberOfInput(char* str);
bool isNumber(char* str);
int main()
{
char str[512];
while(1)
{
printf("Enter text: ");
fgets(str, 512, stdin);
int numberOfInput = getNumberOfInput(str);
if ( numberOfInput == 0 )
printf("You must give an input\n");
else if ( numberOfInput > 1 )
printf("You have to give exactly one input\n");
else
{
if (!isNumber(str))
printf("The input is not an integer\n");
else
{
int input = atoi(str);
printf("input: %d\n", input);
}
}
}
return 0;
}
int getNumberOfInput(char* str)
{
char* word = strtok(str, " \t\n\v\f\r");
int counter = 0;
while(word != NULL)
{
++counter;
word = strtok(NULL, " \t\n\v\f\r");
}
return counter;
}
bool isNumber(char* str)
{
int i, len = strlen(str);
for (i=0; i<len; ++i)
if (!isdigit(str[i]))
return false;
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.