[英]Value of string was rewritten after read a file which the name is the value of the string
一共有5个txt文件,其中一个(“ table_of_content.txt”)在每四行中包括其他四个txt文件的名称。 在其他四个文件中,每个文件都包含一行句子。
读取表txt并使用数组还原字符串(其他文件的名称)没有问题。
但是,当我尝试使用getline。()恢复其他四个文件中的句子filenames [number]之后,应恢复四个文件名称的字符串被重写,它与word [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 ++没有可变长度数组 。 解决方案是使用std::vector
。
在定义时, number
的值为零 。 因此,您尝试创建一个零元素数组,这是不允许的。 解决方案是在获得number
的最终值后进行定义。
你的words
也有同样的问题。
仔细阅读代码, 一种简单的filenames
解决方案是将其读入临时字符串,然后将字符串推入vector中 。 有更多的紧凑型和“ C ++式”解决方案,但是循环推送是一个好的开始。
也就是说,您的第一个循环可能类似于
std::vector<std::string> filenames;
std::string filename;
while (content >> filename){
filenames.push_back(filename)
}
注意, number
不再需要,因为元件的数量可以通过得到filenames.size()
你应该用words
做类似的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.