【问题标题】:Running through a file to fill a map and splitting on white space运行文件以填充地图并在空白处分割
【发布时间】:2014-10-17 21:21:59
【问题描述】:

所以我有一个项目(我不希望任何人为我做我的硬件,但我现在对 3 个数据结构中的第一个感到厌烦,这样我就可以开始我的项目了)我需要填写一个通过运行一些文件来匹配映射,我的示例文件设置简单,我需要提取一个 long 作为映射中字符串的值的键,如下所示:

0 A

1 B

2 C

我的对显然是 0 的地方是 A 的关键,这将是这个项目的一个字符串,问题是我的导师也说这将是一种可能的格式:

0 W e b 1

1 W e b 2

2 W e b 3

其中 0 是“W e b 1”的键。我知道我需要在空白处进行划分,但老实说,我什至不知道从哪里开始,我尝试了几种方法,但在第二种情况下我只能得到字符串的第一个字符。

这最终是我所坐的,不用担心整个布尔返回以及我知道整个打开文件和检查它应该发生在这个函数之外的事实,但是我的教授希望所有这些都在这个函数中.

bool read_index(map<long, string> &index_map, string file_name)
{
    //create a file stream for the file to be read
    ifstream index_file(file_name);

    //if file doesn't open then return false
    if(!index_file)
        return false;

    string line;
    long n;
    string token;
    //read file
    while(!index_file.eof())
    {
        getline(?)
        //not sure how to handle the return from getline
    }

    //file read?
    return !index_file.fail();
}

【问题讨论】:

  • 马上开始,while(!index_file.eof()) is wrong。使用while(std::getline(index_file, line)) 并在循环体中丢失getline始终检查您的 IO 操作是否成功;永远不要假设他们没有失败。

标签: c++ getline


【解决方案1】:

如果你是一个纯 C 爱好者,你可以使用 strtok() 函数进行行分割,但是有一个很好的旧 C++ 分割文件数据的方法:只需重定向 cin 流式传输到您的文件,它会拆分任何有效的分隔符——空格、制表符、换行符,您只需要为自己保留一个行计数器

std::ifstream in(file_name);
std::streambuf *cinbuf = std::cin.rdbuf(); //better save old buf, if needed later
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to file_name

// <something>

std::string line;
while(std::getline(std::cin, line))  //now the input is from the file
{
    // do whatever you need with line here, 
    // just find a way to distinguish key from value
    // or some other logic
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2022-09-28
    • 2017-02-28
    • 2017-11-23
    • 2014-08-13
    • 2013-07-20
    • 1970-01-01
    相关资源
    最近更新 更多