Hom*_*mer 1 c++ vector fgets char push-back
我想使用push_back函数用文本文件中的行填充我的向量.但它会用最后一行覆盖所有条目.这是源代码:
int main() {
std::vector<char*> lines;
FILE* file;
file = fopen("textfile.txt", "r");
const size_t max_line_length = 1000;
char line[max_line_length + 1];
while ( !feof(file)) {
fgets(line, max_line_length, file);
lines.push_back(line);
}
fclose(file);
}
Run Code Online (Sandbox Code Playgroud)
希望有人可以提供帮助.
你正在覆盖Line,这实际上是你唯一存储的东西,因为你永远不会制作深层拷贝.试试这个:
int main() {
std::vector<std::string> lines; // <- change this!
FILE* file;
file = fopen("textfile.txt", "r");
const size_t max_line_length = 1000;
char line[max_line_length + 1];
while ( !feof(file)) {
fgets(line, max_line_length, file);
lines.push_back(line);
}
fclose(file);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3222 次 |
| 最近记录: |