【问题标题】:Reading .txt file and organizing into two-dimensional array读取.txt文件并组织成二维数组
【发布时间】:2017-05-02 05:10:23
【问题描述】:

我希望获取一个 50 行乘 2 列的有点长的文本文件,让用户输入文件名并将其读入一个二维数组。文本文件是有组织的名称(包括逗号)和数字的组合。
我可以让控制台显示文本文件本身,但是在将数据组织到数组中时我被卡住了。我正在尝试设计一个涉及getlinefind 的循环代码,以便程序通过.txt 排序,在逗号处停止并将该逗号之前的每个字符记录到一个位置(即[0] [0] ) 的数组。我知道使用向量会更容易,但我想用一个数组来解决这个问题。

另外,还有将名称(字符串)读入数组(int)的问题。

【问题讨论】:

  • 显示文件格式。同样存储字符串代替 int 也是不正确的。

标签: c++ arrays file


【解决方案1】:

请测试此代码:

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

template<typename Out>
void split(const std::string &s, char delim, Out result) {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        *(result++) = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}
int main()
{
    std::ifstream file("test.txt", std::ios::binary);
    std::string a, b;
    int c;
    std::vector<std::vector<std::string>> arr;
    if (file)
    {
        while (file >> a )
        {
            std::vector<std::string> v = split(a, ',');
            arr.push_back(v);
        }
    }
    return 0;
}

我的 test.txt:

m,2
n,4
o,6
p,8
q,10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多