【问题标题】:Read text file with different number of words in each line into two dimensional array in C++将每行中具有不同单词数的文本文件读入C++中的二维数组
【发布时间】:2016-05-01 05:13:27
【问题描述】:

所以,我正在尝试将文本文件读入 C++ 中的二维数组。 问题是每行的单词数并不总是一样的,一行最多可以包含11个单词。

例如,输入文件可能包含:

    ZeroZero    ZeroOne    ZeroTwo   ZeroThree
    OneZero     OneOne
    TwoZero     TwoOne     TwoTwo
    ThreeZero
    FourZero    FourOne

因此,array[2][1] 应该包含“TwoOne”,array[1][1] 应该包含“OneOne”,等等。

我不知道如何让我的程序每行增加行号。我显然没有工作:

string myArray[50][11]; //The max, # of lines is 50
ifstream file(FileName);
if (file.fail())
{
    cout << "The file could not be opened\n";
    exit(1);
}
else if (file.is_open())
{
    for (int i = 0; i < 50; ++i)
    {
        for (int j = 0; j < 11; ++j)
        {
            file >> myArray[i][j];
        }
    }
}

【问题讨论】:

  • 读取getline()的行,拆分应该是一种方式。
  • 你为什么不使用vector&lt;vector&lt;string&gt;&gt;?
  • @barakmanos 我猜应该是vector&lt;vector&lt;string&gt; &gt;
  • @MikeCAT:是的,刚刚解决了这个问题。
  • @MikeCAT “应该是一种方式”是什么意思?

标签: c++ arrays multidimensional-array readfile


【解决方案1】:

您应该使用vector&lt;vector&lt;string&gt;&gt; 来存储数据,因为您事先不知道要读取多少数据。

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
    const string FileName = "a.txt";
    ifstream fin ( FileName );
    if ( fin.fail() )
    {
        cout << "The file could not be opened\n";
        exit ( 1 );
    }
    else if ( fin.is_open() )
    {
        vector<vector<string>> myArray;
        string line;
        while ( getline ( fin, line ) )
        {
            myArray.push_back ( vector<string>() );
            stringstream ss ( line );
            string word;
            while ( ss >> word )
            {
                myArray.back().push_back ( word );
            }
        }

        for ( size_t i = 0; i < myArray.size(); i++ )
        {
            for ( size_t j = 0; j < myArray[i].size(); j++ )
            {
                cout << myArray[i][j] << " ";
            }
            cout << endl;
        }
    }

}

【讨论】:

  • 谢谢!我不知道向量,这就是我尝试使用数组的原因。我想我必须对向量进行一些研究。你的回答很有帮助。再次感谢!
  • @Jack 很高兴这对您有所帮助!
猜你喜欢
  • 2019-03-24
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 2020-04-20
  • 2015-05-16
  • 2013-03-11
  • 2013-11-18
相关资源
最近更新 更多