C语言读取文件时字符串打印首字符重复异常求助
Hey there! Let's break down what's going on with your code—you're super close, just a small mix-up with how you're storing strings in C that's causing those weird repeated first characters.
The Root Cause
In C, a string is a sequence of characters ending with a null terminator (\0). When you declared:
char registracka[1000], mesic[1000];
You created arrays of single characters, not arrays of strings. So registracka[i] is just one char, not a space to hold an entire string like "ABC-12-34".
When you used scanf("%s", ®istracka[i]), you told scanf to write the entire string starting at the address of that single char. This overwrites the memory of the following elements in the array. When you later print with %s, it reads from registracka[i] until it hits a null terminator—so it's pulling in characters from the strings you stored in later positions, causing the repeated leading characters you see.
Fixed Code
Here's the adjusted version of your code, with explanations of the changes:
#include <stdio.h> #include <stdlib.h> int main ( void ) { // Integer arrays stay the same int kamera[1000], den[1000], hodina[1000], minuta[1000]; // Change to 2D char arrays: 1000 elements, each can hold up to 50/10 chars (adjust as needed) char registracka[1000][50], mesic[1000][10]; int i = 0; // Replace !feof(stdin) with checking scanf's return value // scanf returns the number of items successfully read—we expect 6 each time while(scanf("%d: %s %s %d %d: %d", &kamera[i], registracka[i], mesic[i], &den[i], &hodina[i], &minuta[i]) == 6) { i++; } // Print only the number of lines we actually read for(int j = 0; j < i; j++) { printf("%d: %s %s %d %d:%d\n", kamera[j], registracka[j], mesic[j], den[j], hodina[j], minuta[j]); } return 0; }
Key Changes Made:
- 2D Char Arrays:
char registracka[1000][50]creates 1000 separate string buffers, each able to hold 49 characters plus the null terminator. This gives enough space for your license plate and month strings. - Removed Unnecessary
&: When using%swith scanf, you pass the address of the string buffer.registracka[i]already points to the start of the i-th string buffer, so we don't need&. - Fixed Loop Condition: Using
while(!feof(stdin))is a common pitfall—it will run one extra iteration after the last line is read. Checking ifscanfreturns 6 (the number of items we expect) ensures we only incrementiwhen a line is successfully parsed. - Dynamic Printing: Instead of hardcoding 7 print statements, we loop through only the lines we actually read—this works even if your input has more or fewer than 7 lines.
Testing with Your Input
When you run this fixed code with your sample input, it will output exactly what you expected:
10: ABC-12-34 Oct 1 7:30
10: ABC-12-34 Oct 1 7:30
10: ABC-12-34 Oct 1 7:30
10: ABC-12-34 Oct 1 7:30
10: ABC-12-34 Oct 1 7:30
10: ABC-12-34 Oct 1 7:30
内容的提问来源于stack exchange,提问作者Grolldash

