为什么我的程序在尝试运行时会一直崩溃?

时间:2013-11-11 19:43:15

标签: c

我是初学者程序员(大约一周),我的简单程序一直在崩溃。我做错了什么?在我输入小时数之前它崩溃了。请帮忙。

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

int hours;
float wage;
float total[2];

int main()

{

    printf("How many hours have you worked this week?\n");
    fgets(hours, sizeof(hours), stdin);
    sscanf(hours,"%d", &wage);

    if (hours < 40)
        wage = 8.5;
        total[0] = hours * wage;

    printf("You will earn %d dollars", total[0]);

    if (hours >= 40)
        wage = 12.75;
        total[1] = hours * wage;

    printf("You will earn %d dollars", total[1]);

    return 0;
}

4 个答案:

答案 0 :(得分:2)

我认为问题在于:

fgets(hours, sizeof(hours), stdin);

fgets不执行格式化输入,因此它会以Cruel和Unusual Ways崩溃,因为它会尝试使用整数值hours作为指向应该读取的缓冲区的指针。

要解决此问题,请尝试以下操作:

scanf("%d", &hours);

下一行还有一个完全不必要且格式错误的scanf

sscanf(hours,"%d", &wage);

scanf的语法是

scanf(formatting-string, destinations...);

因此,它应该看起来像这样:

scanf("%f", &wage);

你绝对应该提高编译器的警告级别;令我惊讶的是,这编译时没有给你一个警告,解释了一些可疑的东西。

printf语句中的格式说明符也存在问题:

printf("You will earn %d dollars", total[0]);

请注意,total[0]float,而不是int,因此%d不合适。请尝试使用%f

希望这有帮助!

答案 1 :(得分:2)

hour已定义为int,但您使用fgets对其进行初始化,该scanf("%d", &hours); 用于输入字符串。
使用

%f

在所有%d语句中也使用printf代替sscanf,{{1}}也是如此,否则您的程序行为将未定义

7.21.6格式化输入/输出功能

  

如果转换规范无效,则行为未定义.282)如果有任何参数   不是相应转换规范的正确类型,行为是   未定义。

答案 2 :(得分:1)

http://www.cplusplus.com/reference/cstdio/fgets/

fgets获取一个char指针作为第一个参数...你给一个int。这就是崩溃的原因

答案 3 :(得分:0)

fgets期望它的第一个参数是指向char数组的第一个元素的指针,它将保存输入。例如:

char hoursBuf[4]; //room for 3 digits plus 0 terminator
if ( !fgets( hoursBuf, sizeof hoursBuf, stdin ))
{
  // error on input; you really want to verify that your library calls
  // succeed before moving on. 
}

这会将输入保存为字符串或字符序列;为了使用它执行计算,您必须使用其他函数(如strtolsscanf)将其转换为整数类型。

您可以直接使用scanf来避免转换步骤:

if ( scanf( "%d", &hours ) == 1 )
{
  ...
}

scanf将返回成功转换和分配的次数;在上面的例子中,它应该是1.如果它是0,那么用户键入除有效整数之外的其他东西。但是,如果他们输入类似&#34; 12w&#34;的内容,scanf将转换并分配&#34; 12&#34;到hours,返回1,并在输入流中保留w以填充下一个输入。

我更喜欢使用strtol因为它捕获了这些情况:

char *chk; // will point to the first character not converted 
int tmp = (int) strtol( hoursBuf, &chk, 10 );

if ( !isspace( *chk ) && *chk != 0 )
{
  // *chk is not whitespace or 0, meaning the user typed an invalid character
  fprintf( stderr, "%s is not a valid integer string\n", hoursBuf );
}
else
{
  // input was good, so we assign hours:
  hours = tmp;
}

我知道对于那些已经编程了大约一周的人来说,这是很重要的。 C中的I / O可以 &#34;简单&#34;或者&#34;健壮的&#34 ;;你不能两者兼而有之。

相关问题