0

I want to get an input of multiple txt files using ifstream and store it in char* array or vector. I have several test files named test1.txt, test2.txt, test3.txt... So I used a for loop and set file path (string) as "test" + to_string(i) + ".txt" When I get an input string from that text file using get line or >> and print it for testing, the text is printed correctly inside the for loop. I saved the string into the array by using statement like "array[i-1]=str;"

and then when I print the array outside the for loop, the outputs are all same- it prints the string of the last test file. I want to know why is it like this.

I tried changing array into vectors, but it works the same. If I don't use the for loop and set each of filePath and string variable, it works fine but I don't think it's a good way to do that for more than 10 cases.

int main() { 
 char* array[10];
 char str[100]; //it is for the sample cases I randomly made which does  not exceeds 99 chars 

 for(int i=1; i<10; i++){
        string filePath = "Test" + to_string(i) + ".txt";
        ifstream openFile(filePath.data());
        if(openFile.is_open()){
           openFile >> str;
           array[i-1] = str;
           cout << array[i-1] << endl; 
           openFile.close();
        } 
}

cout << array[0] << endl;
cout << array[5] << endl;
cout << array[6] << endl;
//then if I print it here the outputs are all same: string from Test10.
}

for example, if test1.txt = "a", test2.txt = "b" ... test9.txt="i", test10.txt="j"

inside the for loop it is printed correctly => a b c d ... j. but outside the for loop the output is all j.

1
  • On an unrelated note, if you have std::to_string then your std::ifstream constructor also can take a std::string as argument for the filename. They were both introduced at the same time (with the C++11 standard). Commented Apr 29, 2019 at 15:16

1 Answer 1

3

You make all pointers of array point to the very same place: The first character of str.

There are a couple of ways of solving this:

  • Make array an array of arrays that you read directly into
  • Dynamically allocate new memory for each string you read, and copy the string into it
  • A few others...
  • Or the solution I recommend: Use an std::array (or possibly std::vector) of std::string and read directly into the strings.
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.