[英]Value of string was rewritten after read a file which the name is the value of the string
There are 5 txt files, one ("table_of_content.txt") includes the name of other four txt files, in each four successive lines. 一共有5个txt文件,其中一个(“ table_of_content.txt”)在每四行中包括其他四个txt文件的名称。 And in the other four files, each contain one line of sentence.
在其他四个文件中,每个文件都包含一行句子。
There is not problem to read the table txt and use array to restore the string(the names of other files). 读取表txt并使用数组还原字符串(其他文件的名称)没有问题。
But after I try to use getline.() to restore the sentences in the other four files, filenames[number], the string which should restore the name of the four files are rewritten, it become the same as words[number], which restore the sentences. 但是,当我尝试使用getline。()恢复其他四个文件中的句子filenames [number]之后,应恢复四个文件名称的字符串被重写,它与word [number]相同。恢复句子。
I am really confused, which part is wrong? 我真的很困惑,哪一部分错了?
#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;
}
The definition 定义
string filenames[number]
is invalid for two reasons: 无效有两个原因:
C++ doens't have variable-length arrays . C ++没有可变长度数组 。 The solution is to use
std::vector
. 解决方案是使用
std::vector
。
At the time of the definition, the value of number
is zero . 在定义时,
number
的值为零 。 So you attempt to create an array of zero elements, which is not allowed. 因此,您尝试创建一个零元素数组,这是不允许的。 The solution to this is to do the definition after you get the final value of
number
. 解决方案是在获得
number
的最终值后进行定义。
You have the same problem with words
. 你的
words
也有同样的问题。
Reading the code a little closer, one simple solution for filenames
is to read into a temporary string and then push the string into the vector . 仔细阅读代码, 一种简单的
filenames
解决方案是将其读入临时字符串,然后将字符串推入vector中 。 There are more compact and "C++'ish" solutions, but pushing in a loop is a good start. 有更多的紧凑型和“ C ++式”解决方案,但是循环推送是一个好的开始。
That is, you first loop could be something like 也就是说,您的第一个循环可能类似于
std::vector<std::string> filenames;
std::string filename;
while (content >> filename){
filenames.push_back(filename)
}
Note that number
is no longer needed, since the number of elements can be gotten by filenames.size()
. 注意,
number
不再需要,因为元件的数量可以通过得到filenames.size()
You should do something similar with words
. 你应该用
words
做类似的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.