如何在Do While循环中修复分段错误

时间:2019-06-22 11:56:12

标签: c

我正在编写一个程序,该程序接受4位员工的ID,一个月的总工作时间以及每小时收到的金额。预期的输出是打印特定月份的员工ID和薪水(带两位小数)。

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

int main()
{
   int id, workedHours;
   float payHour, payMonth;

   do
   {
      printf("Please enter your ID: ");
       scanf("%d", &id);
  }
   while (strlen(id) != 4);

  printf("Please enter your worked hours: ");
  scanf("%d", &workedHours);
  printf("Please enter the amount you received per hour: $");
  scanf("%f", &payHour);

  payMonth = payHour * workedHours;

  printf("ID: %d\n", id);
  printf("Salary: $%.2f\n", payMonth);
  return(0);
}

1 个答案:

答案 0 :(得分:0)

一种选择是使用%n指定符来记录扫描处理的字符数。格式字符串" %n%d%n"将跳过任何前导空格,记录到此为止已处理的字符数,扫描int并再次记录已处理的字符数。
scanf代表一项可以返回1(成功),0(无法解析该值)或EOF(文件结束)。如果返回值为0,则必须清除输入中的待处理字符。

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

int main()
{
    int id, workedHours;
    int first = 0;
    int last = 0;
    int result = 0;
    float payHour, payMonth;

    do
    {
        printf("Please enter your ID: ");
        fflush ( stdout);
        result = scanf ( " %n%d%n", &first, &id, &last);
        if ( result == EOF)
        {
            return 0;
        }
        if ( result == 0)
        {
            while ( getchar ( ) != '\n')
            {
                //clean input
            }
        }
    }
    while ( result != 1 || last - first != 4);

    do
    {
        printf("Please enter your worked hours: ");
        fflush ( stdout);
        result = scanf("%d", &workedHours);
        if ( result == EOF)
        {
            return 0;
        }
        if ( result == 0)
        {
            while ( getchar ( ) != '\n')
            {
                //clean input
            }
        }
    }
    while ( result != 1);

    do
    {
        printf("Please enter the amount you received per hour: $");
        fflush ( stdout);
        result = scanf("%f", &payHour);
        if ( result == EOF)
        {
            return 0;
        }
        if ( result == 0)
        {
            while ( getchar ( ) != '\n')
            {
                //clean input
            }
        }
    }
    while ( result != 1);

    payMonth = payHour * workedHours;

    printf("ID: %04d\n", id);
    printf("Salary: $%.2f\n", payMonth);

    return(0);
}