簡體   English   中英

如何使用C ++讀取txt文件並將其放在數組上?

[英]How to read a txt file and put it on a array with c++?

我有這個.txt文件,其中包含很多單詞(每行一個)。 我試過了

ifstream myReadFile;
myReadFile.open("restrict_words.txt");
char output[100];
if (myReadFile.is_open()) {
     while (!myReadFile.eof()) {
          printf("mamao");
          myReadFile >> output;
          cout<<output;
     }
}

但是我不知道如何使它像...那樣工作。

我想要做

while(reading){
     stringArray.add(file.line);
}

我怎樣才能做到這一點?

首先,這:( (!myReadFile.eof())是錯誤的 有關原因,請參見鏈接。 第二。 如果您只想將字符串文件加載到數組中,則可以這樣做:

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>

int main()
{
    std::ifstream inp("restrict_words.txt");
    std::istream_iterator<std::string> inp_it(inp), inp_eof;
    std::vector<std::string> words(inp_it, inp_eof);

    // words now has ever whitespace separated string 
    //  from the input file as a vector entry
    for (auto s : words)
        std::cout << s << '\n';
}

建議閱讀:

你是這個意思嗎

//untested
#include <vector>
#include <fstream>
#include <string>
#include <iostream> //edited

int main()
{
    std::ifstream ist("restrict_words.txt");
    std::string word;
    std::vector<std::string> readWords;
    while(ist >> word)
        readWords.push_back(word);
    //test
    for(unsigned i = 0; i != readWords.size(); ++i)
        std::cout << readWords.at(i) << '\n';  // or readWords[i] (not range checked)
}

編輯:

對於每一行,您將執行以下操作:

std::string line;
std::vector<std::string> readLines;
while(std::getline(ist, line))
{
    readLines.push_back(line);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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