【问题标题】:Value of string was rewritten after read a file which the name is the value of the string读取名称为字符串值的文件后,字符串的值被重写
【发布时间】: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


【解决方案1】:

定义

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做类似的事情。

【讨论】:

  • 谢谢你的帮助,但是我们还没有学习矢量,要求我们将文件名和单词都存储在数组中,有没有办法使用数组来做到这一点?
  • @FernM 那你得事先设置一个固定的大小,希望够大(但不要大而浪费未使用的空间)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 2016-11-30
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多