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

使用fscanf读取多词名称与整数文本时无法分离内容的问题

Ah, I see the problem here—you made a tiny but critical mistake in your fscanf format string, and that's why the integer is getting stuck in your title string. Let's break this down and fix it step by step.

What Went Wrong with Your Original Code

Your format string "%[^d\n] %d" doesn’t do what you think it does. The %[^d\n] syntax means "match all characters except the lowercase letter 'd' and newline". Since none of your movie titles contain a 'd', this will read the entire line (including the trailing integer) into the title buffer, leaving nothing for the %d to parse. That’s exactly why the integer is ending up in your string!

You probably meant to exclude all digits, not just the letter 'd'. The correct syntax for excluding digits is %[^0-9\n], but even that has a caveat—it will include any spaces before the integer in the title, which you’ll need to clean up later.

The Most Reliable Solution: Read the Whole Line First

Using fscanf directly for input where the first field can contain spaces is error-prone. The best approach is to read the entire line with fgets, then split it into the title and integer. This handles edge cases like multiple spaces between the title and number, and won’t break if a title ever includes a digit (e.g., "Avatar 2").

Here’s the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_TITLE_LEN 256

int main() {
    FILE *ifp = fopen("your_file.txt", "r");
    if (!ifp) {
        perror("Failed to open file");
        return 1;
    }

    char line[MAX_TITLE_LEN + 10]; // Extra space for integer and newline
    char title[MAX_TITLE_LEN];
    int stock;

    while (fgets(line, sizeof(line), ifp) != NULL) {
        // Remove trailing newline if present
        size_t line_len = strlen(line);
        if (line_len > 0 && line[line_len - 1] == '\n') {
            line[line_len - 1] = '\0';
        }

        // Find the last space to split title and stock
        char *last_space = strrchr(line, ' ');
        if (!last_space) {
            fprintf(stderr, "Skipping invalid line: %s\n", line);
            continue;
        }

        // Extract title
        *last_space = '\0';
        strncpy(title, line, MAX_TITLE_LEN - 1);
        title[MAX_TITLE_LEN - 1] = '\0'; // Ensure null-termination

        // Parse integer (safer than atoi with error checking)
        if (sscanf(last_space + 1, "%d", &stock) != 1) {
            fprintf(stderr, "Invalid number in line: %s\n", line);
            continue;
        }

        // Use your parsed values here
        printf("Title: '%s', Stock: %d\n", title, stock);
    }

    fclose(ifp);
    return 0;
}

If You Insist on Using fscanf

If you really want to stick with fscanf, fix the format string and add code to trim trailing spaces from the title:

#include <stdio.h>
#include <string.h>

#define MAX_TITLE_LEN 256

int main() {
    FILE *ifp = fopen("your_file.txt", "r");
    if (!ifp) {
        perror("Failed to open file");
        return 1;
    }

    char title[MAX_TITLE_LEN];
    int stock;

    // %[^0-9] matches all non-digit characters (including leading spaces before the integer)
    while (fscanf(ifp, "%[^0-9] %d", title, &stock) == 2) {
        // Trim trailing spaces from the title
        char *end = title + strlen(title) - 1;
        while (end >= title && *end == ' ') {
            *end = '\0';
            end--;
        }

        printf("Title: '%s', Stock: %d\n", title, stock);
    }

    fclose(ifp);
    return 0;
}

Note: This will fail if any title contains a digit, since %[^0-9] stops at the first digit it encounters.

Recap

Your core mistake was using %[^d\n] instead of %[^0-9\n], but even with that fix, fscanf isn’t the most robust tool for this job. The fgets + split approach is strongly recommended for handling variable-length titles with spaces.

内容的提问来源于stack exchange,提问作者Mona_Amb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:51:39