我想使用ifstream获得多个txt文件的输入,并将其存储在char*数组或向量中。我有几个名为test1.txt、test2.txt、test3.txt的测试文件...因此,我使用了一个for循环,并将文件路径(字符串)设置为"test“+ to_string(i) + ".txt”。当我使用get line或>>从文本文件中获取输入字符串并将其打印出来进行测试时,该文本在for循环中被正确打印出来。我使用类似"arrayi-1=str;“这样的语句将字符串保存到数组中。
然后,当我在for循环外部打印数组时,输出都是相同的-它打印最后一个测试文件的字符串。我想知道为什么是这样的。
我试着把数组改成向量,但效果是一样的。如果我不使用for循环并设置每个filePath和string变量,它可以很好地工作,但我不认为这是一个超过10种情况的好方法。
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.
}例如,如果test1.txt = "a",test2.txt = "b“...test9.txt="i",test10.txt="j“
在=>循环中,它被正确地打印为a b c d ...j,但在for循环之外,输出都是j。
发布于 2019-04-29 23:13:59
您使array的所有指针都指向同一个位置:str的第一个字符。
有几种方法可以解决这个问题:
array一个数组数组,您可以直接读取并为您读取的每个字符串分配新的内存,并将字符串复制到其中std::array >C13的std::array(或可能的std::vector)并直接读取字符串。https://stackoverflow.com/questions/55906086
复制相似问题