C如何使用fstream读取带有空格的制表符分隔文件

新手上路,请多包涵

我需要使用一些 C++ 代码来读取制表符分隔的文本文件。该文件包含三列,第二列包含带空格的字符串。以下是该文件的一些示例。

 1   hellow world    uid_1
2   good morning    uid_2

以下是我需要用来读取文件的 C++。但是,当点击字符串中的空格时,它无法正确读取文件。

关于修改 while 循环以使其工作的任何建议?我不熟悉C++。请提供详细代码。谢谢!

 #include <Rcpp.h>
#include <iostream>
#include <fstream>
#include <string>

std::ifstream infile (file_name.c_str());

int row = -1;
std::string col;
std::string uid;

while (infile >> row >> col >> uid) {

    ### operations on row, col and uid ####

}

原文由 syd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 518
1 个回答

一种情况如下:

 #include <iostream>
#include <vector>
#include <fstream>
#include <iterator>
#include <sstream>

using namespace std;

// take from http://stackoverflow.com/a/236803/248823
void split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

int main() {
    std::ifstream infile ("./data.asc");

    std::string line;

    while (std::getline(infile, line))
    {
        vector<string> row_values;

        split(line, '\t', row_values);

        for (auto v: row_values)
            cout << v << ',' ;

        cout << endl;
     }

    cout << "hello " << endl;
    return 0;
}

结果是:

 1,hellow world,uid_1,
2,good morning,uid_2,

注意结尾的逗号。不确定你想对文件中的值做什么,所以我只是尽可能简单。

原文由 Marcin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题