C语言结构体中数组存储问题及循环异常求助
Hey there! Let’s tackle those two frustrating issues you’re hitting with your C struct code: that stubborn for loop that only runs once, and the trouble storing multiple class days in an array. I’ll walk through the most common causes and fixes for both.
1. Why Your First For Loop Only Runs Once
The #1 culprit here is almost always leftover newline characters in the input buffer, paired with how scanf handles input. Let’s break it down with a common example of what your code might look like:
// Your original (buggy) code snippet typedef struct { char name[50]; int days[7]; } Course; int main() { Course course; int k; printf("Enter course name: "); scanf("%s", course.name); // Reads until space, leaves newline in buffer printf("How many days? "); scanf("%d", &k); // This loop only runs once? for(int i=0; i<k; i++) { printf("Enter day %d: ", i+1); scanf("%d", &course.days[i]); } return 0; }
Here’s what’s happening:
- When you enter a course name and press enter,
scanf("%s")reads the text but leaves the\nnewline character in the input buffer. - If your loop relies on user input that gets messed up by these leftover characters (or if you accidentally set
kto 1/0 via bad input), the loop will terminate early.
Fixes for the Loop Issue:
- Use
fgetsfor course names (supports spaces): If your course names have spaces (like "Data Structures"),%swill only read up to the first space.fgetsfixes this, and we can strip the trailing newline:printf("Enter course name: "); fgets(course.name, sizeof(course.name), stdin); // Remove the trailing newline course.name[strcspn(course.name, "\n")] = '\0'; - Clean the input buffer: If you stick with
scanffor course names, add a space before format specifiers (likescanf(" %d", &k)) to skip all whitespace (including newlines), or usegetchar()to eat leftover newlines before reading integers. - Double-check your loop condition: Make sure you didn’t accidentally write
i = kinstead ofi < k, or modify the loop variableiinside the loop by mistake.
2. Trouble Storing Multiple Class Days in the Array
Most issues here stem from array size limits, out-of-bounds access, or missing input validation. Let’s cover the key fixes:
Common Causes & Fixes:
- Your array is too small: If you defined
int days[1];in your struct, you can only store one day—any extra entries will overwrite other memory (undefined behavior). Define it to hold up to 7 days (one for each weekday):int days[7];. - No tracking of valid entries: Add a
day_countfield to your struct to keep track of how many days you actually stored, instead of relying on a loop variable that might be wrong:typedef struct { char name[100]; int days[7]; int day_count; // Tracks how many days are valid } Course; - Unvalidated input: If users enter non-integers or numbers outside 1-7,
scanfwill fail, leaving garbage values in your array. Add checks to ensure valid input:int day; // Make sure we read a valid day (1-7) if(scanf("%d", &day) != 1 || day < 1 || day >7) { printf("Invalid day! Enter 1-7.\n"); i--; // Let the loop retry this entry while(getchar() != '\n'); // Clear invalid input from buffer continue; } course.days[i] = day; - Out-of-bounds access: Never let your loop run more times than your array can hold. For example, if your array has 7 slots, cap
kat 7 with input validation:printf("How many days? "); while(scanf("%d", &k) !=1 || k <1 || k>7) { printf("Enter a number between 1 and 7: "); while(getchar() != '\n'); } course.day_count = k;
Full Working Example
Here’s a polished version of your code that fixes both issues:
#include <stdio.h> #include <string.h> typedef struct { char name[100]; int days[7]; int day_count; } Course; int main() { Course my_course; // Read course name (supports spaces) printf("Enter course name: "); fgets(my_course.name, sizeof(my_course.name), stdin); my_course.name[strcspn(my_course.name, "\n")] = '\0'; // Read number of days (validated) int num_days; printf("How many days does this course meet? "); while(scanf("%d", &num_days) !=1 || num_days <1 || num_days>7) { printf("Invalid input! Enter 1-7: "); while(getchar() != '\n'); } my_course.day_count = num_days; // Read each day (validated) printf("Enter each day (1=Mon, 2=Tue, ...7=Sun):\n"); for(int i=0; i<my_course.day_count; i++) { int day; printf("Day %d: ", i+1); while(scanf("%d", &day) !=1 || day <1 || day>7) { printf("Invalid day! Enter 1-7: "); while(getchar() != '\n'); } my_course.days[i] = day; } // Verify the output printf("\n--- Course Details ---\n"); printf("Name: %s\n", my_course.name); printf("Meets on: "); for(int i=0; i<my_course.day_count; i++) { switch(my_course.days[i]) { case 1: printf("Monday "); break; case 2: printf("Tuesday "); break; case 3: printf("Wednesday "); break; case 4: printf("Thursday "); break; case 5: printf("Friday "); break; case 6: printf("Saturday "); break; case 7: printf("Sunday "); break; } } printf("\n"); return 0; }
Give this a try—your loop should run the correct number of times, and your class days will be stored safely in the array.
内容的提问来源于stack exchange,提问作者Maisie Farro

