You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Your lineCount resets to 1 every loop iteration, so it can never correctly track the actual line number for error reporting.
  2. 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).
  3. Your current sscanf format 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: lineCount is initialized outside the loop and increments after each line, so error messages reference the correct line.
  • FRNO validation: The sscanf format explicitly includes FRNO—if the line doesn't have this token in the right position, sscanf returns fewer than 6, and we flag the line as invalid.
  • Email validation: We read the full email address, then use strchr to check for the @ symbol. If it's missing, we reject the line.
  • Email username extraction: We copy the portion of the email before @ into emailUser to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:32:54