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.
std::to_stringthen yourstd::ifstreamconstructor also can take astd::stringas argument for the filename. They were both introduced at the same time (with the C++11 standard).