[英]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
。
希望這可以幫助!
hour
是int
定義的,但是您正在使用fgets
初始化它,該fgets
用於輸入字符串。
采用
scanf("%d", &hours);
還請在所有printf
語句中使用%f
而不是%d
,因此對於sscanf
否則程序的行為將為Undefined 。
如果轉換規范無效,則行為是不確定的。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.
}
這會將輸入保存為字符串或字符序列; 為了使用它執行計算,您將不得不使用諸如strtol
或sscanf
另一個函數將其轉換為整數類型。
您可以通過直接使用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.