在C语言中,解决从字母表输入整数并重复循环

时间:2014-11-17 14:49:10

标签: c++ input integer

抱歉,我犯了一个错误,我使用的是C ++,但是我正在使用C语言。我正在编写一个关于计算某些公式的程序代码。首先,我设置了一个供用户选择的菜单。然后我让他们从3个公式中选择。示例压力=力/面积。我想从用户那里得到force和area的值为float。我想对它进行编程,好像force大于或等于0,程序继续询问区域的值。否则,显示错误并询问相同的问题。我测试了我的程序,如果我输入负值,它就可以工作。但如果我输入一个单词,程序就会重复循环不可阻挡。

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
int menu_selection,error_flag,repeater;
float force, area, pressure;

printf("Please select a formula. [0 - 3]\n>>");
scanf("%d",&menu_selection);
if(menu_selection==1)
    {
    error_flag=0;
    system("cls"); 

    printf("Pressure's formula\n\n");
        do{
            error_flag=0;
            printf("Please key in the force applied.(N)\n>>");
            scanf("%f",&force);
            if(force>0)
            {
                printf("Please key in the surface area.(m^2)\n>>");
                scanf("%f",&area);

                pressure = force/area;

                printf("The pressure is %.2fPa.\n\n",pressure);
            }
            else
            {
                error_flag=1;
                printf("Invalid input, please key in a positive number.");
            }
        }while(error_flag==1);
    }

当我输入字母,单词&#34;输入无效时,请输入正数。&#34;在控制台发送垃圾邮件,系统出错了。我知道它的数据类型问题。怎么解决?请帮忙!!如果您为我提供完整的解决方案,谢谢。感谢。

2 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <iostream>    // Include the iostream for cin

int main(void)
{
    int menu_selection, error_flag;
    float force, area, pressure;

    printf("Please select a formula. [0 - 3]\n>>");
    scanf("%d", &menu_selection);
    if (menu_selection == 1)
    {
        error_flag = 0;
        system("cls");

        printf("Pressure's formula\n\n");
        do{
            error_flag = 0;
            printf("Please key in the force applied.(N)\n>>");
            std::cin >> force;                     // Read value into force
            if (std::cin.good() && force >= 0)                  // Verify the force is of type float. cin will set its failbit if the user does not input the proper data type.
            {
                printf("Please key in the surface area.(m^2)\n>>");
                scanf("%f", &area);

                pressure = force / area;

                printf("The pressure is %.2fPa.\n\n", pressure);
            }
            else
            {
                error_flag = 1;
                printf("Invalid input, please key in a positive number.\n");
                std::cin.clear();                   // Clears the failbit
                std::cin.ignore(INT_MAX, '\n');     // Flushes the cin stream
            }
        } while (error_flag == 1);
    }

    return 0;
}

答案 1 :(得分:0)

修改:实际答案为here。这是重复的。您的问题是由于scanf在输入缓冲区失败时没有消耗输入缓冲区中的内容,因此每次都重新读取它并再次失败。