c++ linux ifstream 读取csv文件

标签 c++ linux g++ ifstream

void Lexicon::buildMapFromFile(string filename )  //map
{
    ifstream file;
    file.open(filename.c_str() );
    string wow, mem, key;
    unsigned int x = 0;

    while(true) {
        getline(file, wow);
        if (file.fail()) break; //check for error
        while (x < wow.length() ) {
            if (wow[x] == ',') {
                key = mem;
                mem.clear();
                x++; //step over ','
            } else 
                mem += wow[x++];
        }

        list_map0.put(key, mem); //char to string
        list_map1.put(mem, key); //string to char
        mem.clear(); //reset memory
        x = 0;//reset index
    }
    file.close();
}

此函数读取一个 2 列的 csv 文件并创建一个以 column1 为键的 column2 的映射。我用 g++ 编译并且文件在大学文件共享上,当我用 ./foo 运行程序时,csv 文件 [在与 foo 相同的目录文件夹中] 没有被读取...为什么?

最佳答案

也许您没有该文件的读取权限。发出命令 ls -l <csv_file> 看看你是否有权利阅读。有关文件权限的更多信息,请参阅此链接 https://help.ubuntu.com/community/FilePermissions

尝试下面的代码对我来说是完美的

   #include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#include <fstream>
using namespace std;


int main(void )  //map
{
   map<string, string> list_map0;

   map<string, string> list_map1;
    string filename = "csv";
    ifstream file;
    file.open(filename.c_str() );
    string wow, mem, key;
    unsigned int x = 0;

    while(true) {
        getline(file, wow);
        if (file.fail()) break; //check for error
        while (x < wow.length() ) {
            if (wow[x] == ',') {
                key = mem;
                mem.clear();
                x++; //step over ','
            } else
                mem += wow[x++];
        }

        list_map0[key] = mem; //char to string
        list_map1[mem] = key; //string to char
        mem.clear(); //reset memory
        x = 0;//reset index
    }
    printf("%d\n", list_map0.size());
    file.close();
}

关于c++ linux ifstream 读取csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14283751/

相关文章:

python - 当前使用我的flask/python webAPI的用户名

c++ - 与 OpenCV 和 MinGW 的 asmlibrary

c++ - 静态初始化困惑

c++ - OpenGL 中没有显示任何内容

linux - 字符串分割并提取bash中的最后一个字段

linux - 如何从 gdb 中自动重新连接到由 valgrind 控制的进程?

c++ - 为什么 std::string 空代表是这样的?

c++ - 使用指向自身的指针初始化成员变量

linux - 生成文件 g++ : fatal error: no input files

c++ - 在 C++ 中实现具有相同方法名称和不同参数的多个接口(interface)