【问题标题】:How to read integer values separated by different delimiters on each line in a file?如何读取文件中每一行上由不同分隔符分隔的整数值?
【发布时间】:2021-04-24 15:47:22
【问题描述】:

我有一个文本文件,其中包含整数值,每行用不同的字符分隔。

所以用户输入文件名,然后调用一个获取文件名的函数并返回读取的所有整数值的总和。

在每一行都提示用户输入分隔符。

如果文件打开失败,函数getSum() 应该通过错误输出流对象报告并返回-1

这是我尝试过的:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>


int getSum(std::string const& fileName){
    std::ifstream in(fileName);
    if(!in){
        std::cerr << "Unable to open input file!\n";
        return -1;
    }

    int sum = 0;
    for(std::string line; std::getline(in, line); ){
        std::cout << "enter separator: ";
        char separator;
        std::cin.get(separator);
        std::istringstream iss(line);
        for(std::string strVal; std::getline(iss, strVal, separator); ){
            sum += std::stoi(strVal);
        }
    }

    return sum;
}


int main(){

    std::string fileName;
    std::cout << "File name: ";
    std::getline(std::cin, fileName);
    std::cout << getSum(fileName) << '\n';


    std::cout << '\n';
}

输入文件:data.txt:

25 20 16
7 0 3

分隔符:' '

输出:

68

为什么不是猜测的71

如果我创建char separator= ' '; 并删除std::cin.get(separator);,它会给我正确的输出:71。所以我想问题出在std::cin.get(separator)

那么有解决办法吗?

【问题讨论】:

    标签: c++ fstream


    【解决方案1】:

    问题来了:

    int getSum(std::string const& fileName){
        std::ifstream in(fileName);
        if(!in){
            std::cerr << "Unable to open input file!\n";
            return -1;
        }
    
        int sum = 0;
        for(std::string line; std::getline(in, line); ){
            std::cout << "enter separator: ";
            char separator;
            std::cin.get(separator); //every time the for-loop loops, this happens again, resetting separator
            std::istringstream iss(line);
            for(std::string strVal; std::getline(iss, strVal, separator); ){
                sum += std::stoi(strVal);
            }
        }
    
        return sum;
    }
    

    这里是修复:

    int getSum(std::string const& fileName) {
        std::ifstream in(fileName);
        if (!in) {
            std::cerr << "Unable to open input file!\n";
            return -1;
        }
    
        int sum = 0;
        std::cout << "enter separator: ";
        char separator;
        separator = std::cin.get(); //get separator BEFORE the for-loop
    
        for (std::string line; std::getline(in, line); ) {
            std::istringstream iss(line);
            for (std::string strVal; std::getline(iss, strVal, separator); ) {
                sum += std::stoi(strVal);
            }
        }
    
        return sum;
    }
    

    它现在按预期输出了 71。

    【讨论】:

    • 问题是我想在每一行输入一次separator。例如文件包含:25;16; 7 0 3 所以第一行分隔符是一个分号,但第二行是一个空格。
    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 2019-12-07
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多