c ++初始化数组存储大小

时间:2014-08-25 14:55:09

标签: c++ arrays

void start ( string fname )
{   
    string FirstElement;    
    int count = 0 ;
    fstream Infile;
    Infile.open( fname.c_str(), ios::in ); // Open the input file 

    while(!Infile.eof()) // using while to look for the total lines
    {
        count++;
    }

    //read to the array
    string data_array[]; //initializing an array
    for(int i=0; !Infile.eof(); i++){
        Infile >> data_array[i]; // storing the value read from file to array

    }

    //Display the array
//    for(int i=1; i<11; i++){
    //    cout << data_array[i] << endl;

    //}
    cout << data_array[0] << endl;
    cout << count << endl;
    return;

}

我有一个文本文件包含逐行的值 我的计划是使用while循环来计算行数 并将其放在“string data_array []”中,但不知怎的,它不会那样工作。 任何人都可以告诉我如何以一种方式制作它可以根据文本文件中的值的数量灵活存储大小?感谢

1 个答案:

答案 0 :(得分:2)

对于灵活存储空间,您可以使用STL的容器,例如std::vector<T>std::list<T>。其他问题在内联评论中突出显示。

// pass by reference
void start(const std::string& fname)
{       
    // use std::ifstream, instead of std::fstream(..., std::ios::in);
    std::ifstream Infile(fname.c_str()); 

    // prefer std::vector to raw array
    std::vector<std::string> data_array; 
    std::string line;

    // read line by line
    while (std::getline(Infile, line)) 
    {
        data_array.push_back(line); // store each line
    }

    // print out size
    std::cout << data_array.size() << std::endl;

    // display the array, note: indexing starts from 0 not 1 !
    for(int i = 0; i < data_array.size(); ++i)
    {
       std::cout << data_array[i] << std::endl;
    }
}