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

C++如何拆分输入文件中一行的两个整数并存入int变量?

解决C++逐行拆分两个整数的问题

方案一:用find()和substr()实现(贴合你的思路)

你之前的代码里,substr()的用法有误,它的参数是「起始索引」和「截取长度」。空格前的数值是从字符串开头(索引0)到空格位置的部分,直接用substr(0, space_pos)就能截取,再转成int即可。修正后的代码如下:

if (argc < 3) 
{
    throw std::invalid_argument("Usage: ./hello <INPUT FILE> <OUTPUT FILE>");
}

ifstream input;
ofstream output;

input.open(argv[1]);
output.open(argv[2]);

// 检查文件是否成功打开
if (!input.is_open()) {
    throw std::invalid_argument("Failed to open input file");
}
if (!output.is_open()) {
    throw std::invalid_argument("Failed to open output file");
}

string command;
// 用size_t匹配find()的返回类型,避免类型警告
size_t space_pos;
int length, rank;

while(getline(input, command)) 
{
    space_pos = command.find(' '); // 直接用字符' '更高效
    // 处理无空格的异常行,避免崩溃
    if (space_pos == string::npos) {
        continue;
    }
    // 截取空格前的部分转成int
    length = stoi(command.substr(0, space_pos));
    rank = stoi(command.substr(space_pos + 1));
    words[length]->print(rank);
}

input.close();
output.close();

方案二:利用输入流自动拆分(更简洁)

C++的输入流会自动跳过空格、换行等空白字符,直接读取整数,完全不需要手动处理字符串拆分,代码更简洁:

if (argc < 3) 
{
    throw std::invalid_argument("Usage: ./hello <INPUT FILE> <OUTPUT FILE>");
}

ifstream input;
ofstream output;

input.open(argv[1]);
output.open(argv[2]);

if (!input.is_open()) {
    throw std::invalid_argument("Failed to open input file");
}
if (!output.is_open()) {
    throw std::invalid_argument("Failed to open output file");
}

int length, rank;
// 直接读取两个整数,直到文件结束
while (input >> length >> rank) {
    words[length]->print(rank);
}

input.close();
output.close();

额外注意点

  • 你代码里的string to_find[100] = {};是未使用的变量,可以直接删除
  • 一定要检查文件是否成功打开,避免后续操作因文件未打开而崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:20:42