簡體   English   中英

我可以在不知道文本文件的列數的情況下以2d數組讀取文件嗎?

[英]Can I read a file in 2d array without knowing the number of columns of a text file?

我想讀取二維數組中的文件。 基本上文件是這樣的

abcedf
ghijkl
諾克雷

現在我知道文件的行,但我不知道列,但列號對於所有行都是相同的。 現在,如果我這樣做。

 for (int i = 0; i < row_size; i++){

 fin>>value;
 row[i]=growfunction 
 }

使用此程序,將繼續將所有文件行添加到第一行,因為沒有條件,因此我可以使其移至第二行。 我能做什么?

感謝您的時間。

最好的方法是將整行直接讀取為字符串,然后使用std :: strstream將該行的元素輸入到數組中的各個值中。

#include <iostream>
#include <sstream>

int main(int argc, char* argv[]) {

  std::string line;
  while(std::getline(std::cin, line)) {
    int rowSize = line.size();
    char * row = new char[rowSize];
    std::strringstream strm;
    strm << line;
    for (int i = 0; i < rowSize; ++i) {
      strm >> row[i];
    }
  }
}

暫無
暫無

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

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