当我在函数isFloat(char array[])
中输入任何结果为false的时,我需要按两次回车键才能保持程序运行。
如果我注释掉除fget()
命令之外的所有内容,则everything要求我按两次回车键。是什么原因造成的?我正在正确地冲洗stdin
,n
被strtok()
移除。printf()
功能是否导致问题?我读到scanf()
和fgets()
一起使用时会产生问题。但在这里他们不是。
问题区域
printf("first number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "n");
success = isFloat(input);
if(success)
firstNum = atof(input);
完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int isFloat(char array[])
{
int m = 0;
int periodCount = 0;
for(m=0; array[m] != ' 00'; m++)
{
if(array[m] == '1' || array[m] == '2' || array[m] == '3' || array[m] == '4' || array[m] == '5' || array[m] == '6' || array[m] == '7' || array[m] == '8' || array[m] == '9' || array[m] == '0')
{
}
else
{
if(array[m] == '.' && periodCount == 0 && m != 0 && m+1 != 'n')
periodCount = 1;
else
return 0;
}
}
return 1;
}
void eatLine()
{
while (getchar() != 'n');
}
int main()
{
double firstNum = 0.0;
double secondNum = 0.0;
double totalNum = 0.0;
int success = 0;
int TEN_THOUSAND = 10000;
char input[TEN_THOUSAND];
//Outputs assignment header
printf("CS201 - Lab 2 - Number Addernn");
printf("first number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "n");
success = isFloat(input);
if(success)
firstNum = atof(input);
while(!success)
{
eatLine();
//The one is for testing purposes
printf("-- bad input --n");
printf("first number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "n");
success = isFloat(input);
if(success)
firstNum = atof(input);
}
printf("second number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "n");
success = isFloat(input);
if(success)
secondNum = atof(input);
while(!success)
{
eatLine();
//The one is for testing purposes
printf("-- bad input --n");
printf("second number: ");
fgets(input, TEN_THOUSAND, stdin);
strtok(input, "n");
success = isFloat(input);
if(success)
secondNum = atof(input);
}
//adds the numbers
totalNum = firstNum + secondNum;
//Solves ugly formatting problem by firstly including a newline
//after the input is garnered. then it outputs firstNum and totalNum
//in a field of 11 spaces with a newline terminator. This decrements
//11 to 10 on the secondNum line to compensate for the space that the + takes up.
printf("n%11.2fn", firstNum);
printf("%s%10.2fn", "+", secondNum);
printf("-----------n");
printf("%11.2fnn", totalNum);
return 0;
}
当我在函数
isFloat(char array[])
中输入任何计算结果为false的内容时,我需要按两次回车键来保持程序运行。
这是因为你有一行代码,期望你输入一行文本。
while(!success)
{
eatLine(); // Culprit