簡體   English   中英

讀取名稱為字符串值的文件后,字符串值被重寫

[英]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]

無效有兩個原因:

  1. C ++沒有可變長度數組 解決方案是使用std::vector

  2. 在定義時, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM