如何将来自输入TXT文件的数据读取到2 C 数组中

How to read data from input txt file into 2 C++ arrays?

本文关键字:读取 数据 数组 文件 TXT 何将来 将来 输入      更新时间:2023-10-16

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 的新手。任何帮助将不胜感激。

这将需要一个基本的读取文件循环,该循环将逐行读取文件,然后按空格将其拆分。对于它将其推到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)        
}

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