C语言读取输入文件提取指定内容并输出?代码过滤问题求助
Hey there! Let's fix your code to handle those invalid lines and get it working reliably. First, let's break down the key issues in your current implementation:
- Your
lineCountresets to 1 every loop iteration, so it can never correctly track the actual line number for error reporting. - You're not checking the return value of
sscanf—this is critical for verifying if the line matches your expected format (including the presence of FRNO). - Your current
sscanfformat doesn't explicitly validate the FRNO token, and it only captures part of the email (before the @) instead of the full address, making it impossible to check for the required @ symbol.
Here's a revised version of your code that addresses all these problems, plus proper validation for both invalid line types:
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> int main() { FILE *fp = fopen("input.txt", "r"); char line[500]; if (!fp) { printf("Can't open input file\n"); exit(EXIT_FAILURE); } int lineCount = 1; // Track line numbers correctly outside the loop while (fgets(line, sizeof(line), fp)) { char fName[12], lName[12]; char email[50]; // Larger buffer to hold full email addresses char area[4], mid[4], end[5]; char emailUser[50]; // Store the username part of the email (before @) // Parse the line with explicit FRNO check // Format breakdown: // %11s: First name (max 11 chars) // %11s: Last name (max 11 chars) // %*s: Skip the ID number (no need to store) // %49s: Full email address (max 49 chars to leave room for null terminator) // FRNO: Explicitly match this token—missing it will make sscanf fail // %3s-%3s-%4s: Split phone number into area code, middle 3 digits, last 4 digits int parseResult = sscanf(line, "%11s %11s %*s %49s FRNO %3s-%3s-%4s", fName, lName, email, area, mid, end); // Check if parsing succeeded (we expect 6 variables to be assigned) if (parseResult != 6) { printf("Invalid line %d: Missing FRNO or incorrect format\n", lineCount); lineCount++; continue; } // Validate email contains @ symbol char *atSymbol = strchr(email, '@'); if (atSymbol == NULL) { printf("Invalid line %d: Email missing @ symbol\n", lineCount); lineCount++; continue; } // Extract the username part of the email (before @) strncpy(emailUser, email, atSymbol - email); emailUser[atSymbol - email] = '\0'; // Ensure the string is null-terminated // Print the final formatted output printf("%s %s %s (%s)%s-%s\n", emailUser, fName, lName, area, mid, end); lineCount++; } fclose(fp); return EXIT_SUCCESS; }
Let's walk through the key improvements:
- Accurate line numbering:
lineCountis initialized outside the loop and increments after each line, so error messages reference the correct line. - FRNO validation: The
sscanfformat explicitly includesFRNO—if the line doesn't have this token in the right position,sscanfreturns fewer than 6, and we flag the line as invalid. - Email validation: We read the full email address, then use
strchrto check for the @ symbol. If it's missing, we reject the line. - Email username extraction: We copy the portion of the email before @ into
emailUserto match your desired output format. - Reliable parsing: Checking
sscanf's return value ensures only lines matching your full expected structure are processed. - Buffer sizing: We increased email buffers to handle real-world email lengths (your original 9-char buffer was too small for most valid addresses).
This code will now:
- Only process lines that contain the FRNO token in the correct position
- Reject any lines where the email lacks an @ symbol
- Output the exact format you want for valid lines
- Print clear error messages with line numbers for invalid lines
内容的提问来源于stack exchange,提问作者AHunt
相关产品推荐
相关产品推荐

