這是輸入字符串和應該讀取文件的代碼。當我在家中使用最新的Dev C++進行編譯時,它運行得非常完美。但是我的學校的Dev C++在i = 9時崩潰了程序(並且在調試後我知道它是)。這是哪一行Michael Nguyen 71 70 91 93 28
。運行時錯誤,數組中的輸入字符串
我通過將char studentFirst[15]
更改爲char studentFirst[17]
來修復它。然而,應該放在Michael
和Nguyen
中的名稱每個不超過14個字符。有人可以幫我看看它。我是否明白這行錯誤fscanf(inFile, "%s%s", studentFirst, studentLast)
?
輸入:
Sidra Amartey 90 88 70 74 70
Rebecca Brown 85 98 73 78 74
Leslie Carter 92 73 86 36 87
Ashley Guillen 95 26 90 83 85
Ryan Hilliard 75 66 69 100 52
Dawn Hopkins 84 69 66 88 74
Kyle Jiwani 7 99 96 84 89
Melvin Johnson 73 80 63 38 88
Edward Maun 82 85 72 75 99
Angelo Morrison 95 97 80 31 70
Michael Nguyen 71 70 91 93 28
Zack Nutt 82 85 97 74 98
Diana Patel 77 70 88 68 82
Patrick Perez 87 77 21 88 7
Abigail Peterson 64 81 75 85 70
Jennifer Putnam 39 91 85 80 70
Kimberly Sanjel 64 69 74 97 12
Marisa Santos 63 77 90 15 60
Hannah Shrestha 13 77 95 97 99
Linda Stoll 50 85 72 91 23
Victoria Taylor 95 93 74 63 90
Haily Wright 80 90 99 68 84
代碼:
int loadStudentNamesGrades(studentnode students[], const char * fileName)
{
FILE * inFile;
char studentFirst[15] = {0};
char studentLast[15] = {0};
int numStudents = 0;
int i = 0, j = 0;
if((inFile = fopen(fileName, "r")) == NULL)
{
printf("Cannot access file %s\n", fileName);
system("PAUSE");
exit(1);
}
for(i = 0; i < MAX_STUDENTS && (fscanf(inFile, "%s%s", studentFirst, studentLast) == 2); i++, numStudents++)
{
for(j = 0; j < MAX_GRADES; j++)
{
fscanf(inFile, "%d", &students[i].grades[j]);
}
students[i].name = (char*)malloc(strlen(studentFirst) + strlen(studentLast) + 2);
strcpy(students[i].name, strcat(strcat(studentFirst, " "), studentLast));
}
return numStudents;
}
'strcat(strcat(studentFirst,「」),studentLast)需要超過15個' – BLUEPIXY
因此,在我的編譯器中有一個選項可以幫助修復這個問題。謝謝BLUEPIXY,非常瞭解您!我搞砸了大部分時間...我希望我的編譯器在家裏不會自動修復這類問題。這是一個不可接受的錯誤。 –
您的編譯器不會「修復」它。你有什麼是未定義的行爲。 UB意味着不能保證會發生任何特定的行爲。所以不會產生錯誤是完全有效的,你不能以任何方式責怪編譯器。 – kaylum