当我在函数isFloat(char array[])
中输入任何评估为false 的时,我需要按两次Enter键以保持程序运行。
如果我注释掉fget()
命令以外的所有内容要求我按两次输入。可能是什么导致了这个?我正在正确刷新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] != '\000'; 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 Adder\n\n");
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.2f\n", firstNum);
printf("%s%10.2f\n", "+", secondNum);
printf("-----------\n");
printf("%11.2f\n\n", totalNum);
return 0;
}
答案 0 :(得分:3)
当我在函数
isFloat(char array[])
中输入任何评估为false的内容时,我需要按两次Enter键以保持程序运行。
那是因为你有一行代码要求你输入一行文字。
while(!success)
{
eatLine(); // Culprit