简体   繁体   中英

Value of string was rewritten after read a file which the name is the value of the string

There are 5 txt files, one ("table_of_content.txt") includes the name of other four txt files, in each four successive lines. And in the other four files, each contain one line of sentence.

There is not problem to read the table txt and use array to restore the string(the names of other files).

But after I try to use getline.() to restore the sentences in the other four files, filenames[number], the string which should restore the name of the four files are rewritten, it become the same as words[number], which restore the sentences.

I am really confused, which part is wrong?

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int main (){
    ifstream content;
    content.open("table_of_content.txt");
    if (content.fail()){
        cout<< "fails";
        return 0;
    }
    int number = 0, i = 0;
    string filenames[number], words[i];
    while (content >> filenames[number]){
        number++;
    }
    content.close();
    cout << number << " students' files are read" << endl;
    // read table_of_content.txt  
    ifstream input;
    while (i < number){
        input.open(filenames[i].c_str());
        getline(input, words[i]);
        // after this getline, filenames become words
        input.close();
        i++;
    }
    cout << filenames[2] << endl << words[3] << endl;
    return 0;
}

The definition

string filenames[number]

is invalid for two reasons:

  1. C++ doens't have variable-length arrays . The solution is to use std::vector .

  2. At the time of the definition, the value of number is zero . So you attempt to create an array of zero elements, which is not allowed. The solution to this is to do the definition after you get the final value of number .

You have the same problem with words .


Reading the code a little closer, one simple solution for filenames is to read into a temporary string and then push the string into the vector . There are more compact and "C++'ish" solutions, but pushing in a loop is a good start.

That is, you first loop could be something like

std::vector<std::string> filenames;
std::string filename;
while (content >> filename){
    filenames.push_back(filename)
}

Note that number is no longer needed, since the number of elements can be gotten by filenames.size() .

You should do something similar with words .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM