我不明白为什么我的指针数组只保存了我正在读取的文件的最后一行。当我将字符串文字替换为 setData() 函数时,代码工作正常。 “mann”文件包含的所有内容都是按字母顺序排列的一堆单词。谢谢。
#include <iostream>
#include <fstream>
using namespace std;
class orignialData {
char* data;
public:
void setData(char* s) { data = s;}
char* getData() const {return data;}
};
class dataClass {
orignialData** W_;
public:
dataClass(char* filename);
void addData();
void viewAll();
};
dataClass::dataClass(char* filename) {
fstream file;
file.open(filename, ios::in);
if (file.fail()) {
cout << "There was an error reading the file...\n";
}
W_ = 0;
W_ = new orignialData*[5];
for (int i = 0; i < 5; i++)
W_[i] = new orignialData;
char buff[30];
char* temp;
while(file >> buff) {
cout << buff << endl;
static int i = 0;
W_[i] -> setData(buff);
i++;
}
file.close();
}
最佳答案
代替 data = s
,编写 data = strdup(s)
来制作内容的拷贝。否则,你会一次又一次地给同一个指针赋值,你会一次又一次地覆盖这个指针指向的内存中的内容。最后,您的临时缓冲区将包含文件的最后一行,并且所有指针都将指向该缓冲区。这就是您正在观察的...
关于c++ - 从文件读取时将数据保存到指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173864/