有 5 个 txt 文件,其中一个(“table_of_content.txt”)包含其他四个 txt 文件的名称,每行连续四行。在其他四个文件中,每个文件包含一行句子。
读表txt用数组还原字符串(其他文件名)没有问题。
但是当我尝试使用getline.()恢复其他四个文件filenames[number]中的语句后,应该恢复四个文件名称的字符串被重写,变成了words[number] ], 恢复句子。
我真的很困惑,哪一部分是错的?
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main (){
ifstream content;
content.open("table_of_content.txt");
if (content.fail()){
cout<< "fails";
return 0;
}
int number = 0, i = 0;
string filenames[number], words[i];
while (content >> filenames[number]){
number++;
}
content.close();
cout << number << " students' files are read" << endl;
// read table_of_content.txt
ifstream input;
while (i < number){
input.open(filenames[i].c_str());
getline(input, words[i]);
// after this getline, filenames become words
input.close();
i++;
}
cout << filenames[2] << endl << words[3] << endl;
return 0;
}
最佳答案
定义
string filenames[number]
无效有两个原因:
C++ 没有 variable-length arrays .解决方案是使用
std::vector
.在定义时,
number
的值为零。所以你试图创建一个零元素数组,这是不允许的。对此的解决方案是在获得number
的最终值后进行定义。
words
也有同样的问题。
仔细阅读代码,一个 filenames
的简单解决方案是读入一个临时字符串,然后 push the string into the vector .有更紧凑和“C++ 风格”的解决方案,但插入循环是一个好的开始。
也就是说,你的第一个循环可能是这样的
std::vector<std::string> filenames;
std::string filename;
while (content >> filename){
filenames.push_back(filename)
}
请注意,不再需要 number
,因为可以通过 filenames.size()
获取元素的数量。
你应该对 words
做一些类似的事情。
关于c++ - 读取名称为字符串值的文件后,字符串值被重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47325533/