0
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;

}

I have a text files contain values lines by lines My plan was to use the while loop to do a total count of the lines and place it in the "string data_array[]" but somehow it doesnt work that way. anyone can advise me on how can I make it in a way that It can have a flexible storage size going according to the numbers of values in the text files? thanks

3
  • you can use vector<string> Commented Aug 25, 2014 at 14:55
  • eof() returning false does not mean the next read will succeed. Check that the last read succeeded before assuming it did. Commented Aug 25, 2014 at 14:56
  • 1
    Your use of eof() is wrong in both places. Just don't use it. Commented Aug 25, 2014 at 15:00

1 Answer 1

2

For flexible storage as you call it, you may use STL's container, such as std::vector<T> or std::list<T>. Other issues are highlighted in inline comments.

// 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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.