c++ - 读取名称为字符串值的文件后,字符串值被重写

标签 c++ arrays string iostream getline

有 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]

无效有两个原因:

  1. C++ 没有 variable-length arrays .解决方案是使用 std::vector .

  2. 在定义时,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/

相关文章:

c++ - 为什么我不能在这个专门的函数模板中将字符串文字传递给 const char* const&

c++ - 如何在qt中解码json

c++ - 打印时前一个指针的值不同

javascript - 通过指定开始和结束字符来拆分字符串

java - java中如何从Map键中获取值

c++ - 根据特征隐藏类模板实例

arrays - 为Kotlin中的每个元素增值

C 程序不在 Windows 上执行。它在 Unix 上

c - 为什么我们可以读取这个分配的指针中的任何字符而不写入它?

c# - 如何检查字符串中不包含在 C# 中的字符