微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用get读取文本文件?

如何解决如何使用get读取文本文件?

我有一个文本文件

$template = Template::find(1);

Module::destroy($template->modules);

$template->delete();

我想将其写入此地图:

a100011
b010100
c001100

问题:如何使用GET()完成它? (这很重要)

map<char,vector<bool>> dict;

解决方法

由于您要处理基于行的数据,因此应使用std::getline()来读取每一行。您可以根据需要使用std::istringstream来解析每一行,例如:

#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <string>

std::map<char,std::vector<bool>> dict;

std::ifstream Dictionary("file.txt");
std::string line;
    
while (std::getline(Dictionary,line))
{
    std::istringstream iss(line);
    std::vector<bool> vec;
    char key,c;
    iss >> key;
    while (iss >> c) vec.push_back(c == '1');
    dict[key] = std::move(vec);
}

Live Demo

,

请勿使用get()

根据您的示例输入,您的记录用换行符分隔,即每条文本行一个记录。因此,按行读取(效率更高)。

std::string text_line;
std::map<char,std::string> database;
while (std::getline(Dictionary,text_line))
{
    const char key = text_line[0];
    text_line.erase(0,1);
    database[key] = text_line;
}

这是一个例子。还有更多std::string方法可用于将键与从文件读取的字符串中的值分开。

,

如果出于某些原因您绝对必须使用get,则可以在下面找到解决方案。您会看到它比Remy Lebeau的解决方案(我曾以此为起点)冗长得多。就我个人而言,我更喜欢检查!='0'副== 1,就好像还有其他数字通常为0且所有其他数字为true一样,但是您更可能希望捕获并带入一个错误条件反正用户的注意。我对雷米的解决方案投了赞成票,该解决方案更容易理解和维护。我确实在输入中添加了对被跳过的空格的检查,您想添加其他逻辑来处理您可能要跳过的其他任何字符或标记错误。根据您可能想使用小于和/或大于来测试范围的数量,以及您可能要使用switch语句。

#include <fstream>
#include <iostream>
#include <map>
#include <vector>

using namespace std;

int main() {
    istream &inFile = cin;
    map<char,std::vector<bool>> dict;
    while(inFile.eof() == false){
        char key = inFile.get();
        if(key == '\n' || key == 0) continue;
        vector<bool> inefficientBitfield;
        char newChar = 'a';
        while(inFile.eof() == false){
            newChar = inFile.get();
            if(newChar == '\n' || newChar == 0) break;
            if(newChar == ' ') continue;
            inefficientBitfield.push_back(!(newChar == '0'));
        }
        dict[key] = move(inefficientBitfield);
            
    }
    
        for(auto &p : dict)
    {
        std::cout << p.first << " =";
        for(auto b : p.second) {
            std::cout << ' ' << std::boolalpha << b;
        }
        std::cout << std::endl;
    }
    
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。