如何将输入txt文件中的数据读入2个C ++数组?

时间:2017-12-01 11:16:28

标签: c++ arrays ifstream

txt文件

1 2 3 4 5 col A 2 3 4 5 6 col B 2 3 4 5 6 col C 2 3 4 5 6 col D 2 3 4 5 6 col E

我已经知道如何将数字存储到2d数组中。但是,这个问题还要求我将单词(包括空格)存储到一维数组中。有人能告诉我怎么做吗?我是C ++的新手。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这将需要一个基本的读取文件循环,它将逐行读取文件,然后用空格分割。对于数字,它将它推送到2d数组,将单词推送到1d数组:

fstream file;
file.open("somefile.txt");
vector<vector<double>> nums;
vector<string> words;
string line;
while(getline(file, line))
{
    vector<double> tempNums;
    istringstream liney(line); int i = 0; string cell;
    while(getline(liney, cell, ' '))
    {
       if(i < 5) tempNums.push_back(stoi(cell.c_str()));
       else words.push_back(" " + cell); 
       i++;
    }
    nums.push_back(tempNums)        
}

希望这会有所帮助。 (这基于上面的格式)