[英]Putting text file content into a 2D array
我正在嘗試將200 x 1000數字的文本文件讀入數組。 每個數字都用制表符分隔。 我認為使用2D數組對這種情況會有所幫助,因為它可以讓我區分各個行。 在這種情況下,能夠區分各個行很重要,這就是為什么我想以這種方式做到這一點。 現在,我有以下內容:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("text.txt");
if(file.is_open())
{
string myArray[1000];
for(int i = 0; i < 1000; ++i)
{
file >> myArray[i];
cout << myArray[i] << endl;
}
}
}
當前將第一行數字掃描到數組中,然后將其打印出來。 我想要一個2D陣列,將每一行掃描到該陣列中,但將它們分開。 這意味着第1行的內容與第2行的內容是分開的。我認為2D數組可以做到這一點。 我在這部分上有些卡住。 我試圖通過使用嵌套的for循環來制作2D數組,但是當我嘗試將值復制到數組中時,事情就開始出錯了。 順序不正確,行未分隔。 我正在用C ++編寫代碼。 如果有人可以幫助我理解如何導入我所描述的文本文檔並將所有信息發送到2D數組,我將不勝感激。 謝謝。
您可以使用stringstream
從每一行中提取數字。 另外,您不需要具有string
s的數組。 您可以只使用一個string
。
int main()
{
ifstream file("text.txt");
if(file.is_open())
{
for(int i = 0; i < 1000; ++i)
{
string row;
if ( std::getline(file, row) )
{
std::istringstream istr(row);
int number;
while ( istr >> number )
{
// Add the number to a container.
// Or print it to stdout.
cout << number << "\t";
}
cout << endl;
}
}
}
}
如果尺寸發生變化,請使用以下代碼。 請注意,您可以使用std::copy
從std::stringstream
復制到std::vector
:
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
int main()
{
std::string input =
"11 12\n"
"21 22\n"
"31 32\n"
"41 42\n"
;
std::stringstream file(input);
std::string temp;
while (std::getline(file, temp)) {
std::stringstream line(temp);
std::vector<std::string> v;
std::copy(
std::istream_iterator<std::string>(line),
std::istream_iterator<std::string>(),
std::back_inserter(v));
for (auto x: v)
std::cout << x << " ";
std::cout << "\n";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.