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

C++多文件读取代码正确性核查请求

你的文件读取代码确实有几个问题,我来帮你梳理并修正~

首先,咱们先说说你代码里最明显的问题:

1. 重复用freopen重定向stdin会导致文件被跳过

你读完symbols.txt之后,连续调用了两次freopen分别绑定dict.txt和handin.txt到stdin——这就意味着dict.txt刚被绑定成标准输入,立刻就被handin.txt替换了,你完全没机会读取字典文件的内容,这肯定不是你想要的结果。而且freopen这种方式会把标准输入的指向改来改去,很容易搞混,不如直接用ifstream单独打开每个文件,每个文件的读取流独立,逻辑更清晰。

2. symbols.txt的读取循环条件逻辑错误

你写的while(cin >> X >> Y && X != '#' )假设终止符#是每行的第一个字符,但根据你的描述,symbols.txt的每行是「大写字母 + 字符串 + #结尾」,比如A apple#。这时候cin >> X会读到A,cin >> Y会读到apple#,你的循环条件判断X != '#'永远不会触发终止,除非某一行开头就是#,这和文件的实际结构不符。

修正后的代码示例

我给你写了一个更稳妥的版本,用独立的文件流处理每个文件,同时正确处理每个文件的#终止符:

#include<bits/stdc++.h>
using namespace std;

int main() {
    // 1. 读取symbols.txt:每行是「大写字母 字符串#」
    ifstream symbols_file("symbols.txt");
    char symbol;
    string mapping_str;
    while (symbols_file >> symbol && symbol != '#') {
        // 读取字符串部分(会包含末尾的#)
        symbols_file >> mapping_str;
        // 去掉字符串末尾的#
        size_t hash_pos = mapping_str.find('#');
        if (hash_pos != string::npos) {
            mapping_str = mapping_str.substr(0, hash_pos);
        }
        // 这里写你的处理逻辑,比如把symbol和mapping_str存到映射表里
        // 例如:symbol_map[symbol] = mapping_str;
    }
    symbols_file.close();

    // 2. 读取dict.txt:每行一个单词,以#结尾
    ifstream dict_file("dict.txt");
    string word;
    while (dict_file >> word && word != "#") {
        // 处理每个单词,比如存入字典集合
        // 例如:dict_set.insert(word);
    }
    dict_file.close();

    // 3. 读取handin.txt:若干数字,以#结尾
    ifstream handin_file("handin.txt");
    string num_str;
    while (handin_file >> num_str && num_str != "#") {
        // 把字符串转成数字
        int num = stoi(num_str);
        // 处理数字的逻辑
    }
    handin_file.close();

    // 4. 写入结果到handout.txt
    ofstream handout_file("handout.txt");
    // 这里写你的输出逻辑,比如把处理结果写入文件
    // 例如:handout_file << result << endl;
    handout_file.close();

    return 0;
}

额外说明

如果symbols.txt里的字符串可能包含空格(比如B hello world#),那上面用cin >> mapping_str的方式会截断字符串,这时候需要改用getline读取整行,同时处理掉cin >> symbol留下的换行符:

// 针对带空格的字符串的读取方式
char symbol;
while (symbols_file >> symbol && symbol != '#') {
    symbols_file.ignore(numeric_limits<streamsize>::max(), ' '); // 跳过符号后的空格
    string line;
    getline(symbols_file, line);
    // 去掉末尾的#
    size_t hash_pos = line.find('#');
    if (hash_pos != string::npos) {
        string mapping_str = line.substr(0, hash_pos);
        // 处理逻辑
    }
}

这样就能正确读取包含空格的字符串啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:07:52