【发布时间】:2018-04-29 17:57:06
【问题描述】:
共有 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;
}
【问题讨论】:
-
Nitpick:你不需要
input.open中的.c_str(),它有一个std::string重载
标签: c++ arrays string iostream getline