簡體   English   中英

當我嘗試運行程序時,為什么我的程序總是崩潰?

[英]How come my program keeps crashing when I try to run it?

我是一名初學者程序員(大約一個星期),我的簡單程序不斷崩潰。 我做錯了什么? 它甚至在我輸入小時數之前就崩潰了。 請幫忙。

#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;
}

我認為問題出在這里:

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

fgets不會執行格式化輸入,因此最終會以殘酷和不尋常的方式崩潰,因為它嘗試使用整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

希望這可以幫助!

hourint定義的,但是您正在使用fgets初始化它,該fgets用於輸入字符串。
采用

scanf("%d", &hours);   

還請在所有printf語句中使用%f而不是%d ,因此對於sscanf否則程序的行為將為Undefined

7.21.6格式化的輸入/輸出功能

如果轉換規范無效,則行為是不確定的。282)如果任何參數不是對應轉換規范的正確類型,則行為是不確定的。

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

fgets將char指針作為第一個參數...您給一個int。 那就是為什么它崩潰

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,則用戶鍵入了有效整數以外的其他內容。 但是,如果他們輸入類似“ 12w”的內容, scanf將轉換並將“ 12”分配給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;
}

我知道對於一個已經進行了大約一周編程的人來說,這是很多東西。 I /在C 0可以 “簡單”或“健壯”; 你不會兩者兼得。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM