创建不带指针的可变大小数组

时间:2017-07-26 13:49:13

标签: c++

我试图从文本文件中读取并使用循环将文本文件中的两行放入字符串数组中。但是我想在不使用指针的情况下将数组(在我的代码中:string abc [5])变成一个可变大小的数组。我对c ++很新,有人可以帮助我。提前谢谢。

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include<sstream>
#include<vector>
using namespace std;

int main() {
string line;
string iss_two;
int i = 0;

ifstream myfile("example.txt");
if (myfile.is_open())
{

    string token;
    stringstream iss;
    int x = 0;
    string abc[5];




        while (getline(myfile, line)) // first read entire line into a 
                                      //string
        {

                abc[i] = line;
                cout << abc[i] << "\n";
                i++;
                //  cout << token;
        }

            //iss.clear();


        cout << "\n" << abc[0];
        cout << "\n" << abc[1];

    myfile.close();

}

else cout << "Unable to open file";
system("pause");
return 0;
}

2 个答案:

答案 0 :(得分:1)

数组(因为单词在C ++语言中使用)不能具有可变大小。它的大小在其生命周期中从未改变。必须在编译时知道数组变量的大小,但可以在运行时确定动态分配的数组的大小。

动态分配需要使用指针变量。您当然可以通过包含类中的功能来隐藏指针的使用。这种抽象数组动态分配的类已经存在于C ++标准库中:std::vector。我建议你使用它。

答案 1 :(得分:0)

  

我想在不使用指针的情况下使数组(在我的代码中:string abc [5])成为可变大小的数组。

如果您 使用数组,您可以通过在编译时预先分配一个非常大的数组来模拟可变大小,然后进行检查以确保您不会使用数组。超过这个数额(即像获得信贷额度)。

const int MAX_ARRAY_SIZE = 100000;
int main() {
   ...
   int linesRead = 0;
   string abc[MAX_ARRAY_SIZE];
      ...
      while (linesRead<MAX_ARRAY_SIZE && getline(myfile, line)) 
      {
          abc[linesRead] = line;
          cout << abc[linesRead] << "\n";
          linesRead++;
      }

      if(linesRead>=MAX_ARRAY_SIZE){
           cout << "Warning!  You hit the maximum array size for your "
                << "string.  There may still be text in your file\n";
      }

      ...

      cout << "\n" << abc[0];
      cout << "\n" << abc[1];
      ...
}

正如其他人所指出的那样,std :: vector库是用C ++设置的。此外,这里的垮台包括预先分配比您需要更多的内存,或者不预先分配您需要的金额。因此,虽然您可以使用此方法开始调试,或者如果您对将要运行的最大数组有一些额外的了解,否则您将使用std :: vector或动态内存分配。

相关问题