C++ 将文本文件内容放入二维数组

C++ 将文本文件内容放入二维数组,c++,arrays,multidimensional-array,C++,Arrays,Multidimensional Array,我试图在一个数组中读取一个200 x 1000的文本文件。每个数字由一个选项卡分隔。我认为使用2D数组对这种情况很好,因为它可以让我区分各个行。在这种情况下,能够区分单独的行是很重要的,这就是为什么我想以这种方式进行操作。现在我有以下几点: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file(

我试图在一个数组中读取一个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;
        }
    }
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream文件(“text.txt”);
if(file.is_open())
{
字符串myArray[1000];
对于(int i=0;i<1000;++i)
{
文件>>myArray[i];

cout您可以使用
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;
            }
        }
    }
}
intmain()
{
ifstream文件(“text.txt”);
if(file.is_open())
{
对于(int i=0;i<1000;++i)
{
字符串行;
if(std::getline(文件,行))
{
std::istringstream istr(世界其他地区);
整数;
while(istr>>编号)
{
//将数字添加到容器中。
//或者打印到标准输出。

cout如果您的维度发生变化,您可以使用以下代码。请注意,您可以使用
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";

  }
}
#包括
#包括
#包括
#包括
int main()
{
字符串输入=
“11 12\n”
“21 22\n”
“31 32\n”
“41 42\n”
;
std::stringstream文件(输入);
std::字符串温度;
while(std::getline(文件,临时)){
标准::串流线(温度);
std::向量v;
复制(
std::istream_迭代器(行),
std::istream_迭代器(),
标准:背部插入器(v);
用于(自动x:v)

std::cout旧的C样式嵌套循环有什么问题吗?为什么是字符串,这些是数字,对吗?使用
文件>>std::ws>>myArray[i];
也许这有帮助:这也可能有帮助: