Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从文本文件读入二维数组_C++_Arrays_Multidimensional Array - Fatal编程技术网

C++ 从文本文件读入二维数组

C++ 从文本文件读入二维数组,c++,arrays,multidimensional-array,C++,Arrays,Multidimensional Array,我有一个文本文件,它包含几行整数,每个整数之间用空格隔开,我想把这些整数读入一个数组,其中每一新行是数组的第一维,该行上的每一个整数都保存到第二维 我的文本文件如下所示: #include <fstream> #include <iostream> #include <sstream> #include <vector> #include <stdexcept> std::vector<std::vector<int>

我有一个文本文件,它包含几行整数,每个整数之间用空格隔开,我想把这些整数读入一个数组,其中每一新行是数组的第一维,该行上的每一个整数都保存到第二维

我的文本文件如下所示:

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <stdexcept>

std::vector<std::vector<int>> get_2d_array_of_ints_from_stream(std::istream& is) {
    std::vector<std::vector<int>> return_value;

    std::string line;
    while(std::getline(is, line)) {   // if this fails, EOF was found or there was an error
        std::istringstream iss(line); // put the line in a stringstream to extract numbers
        int value;                    // temporary used for extraction
        std::vector<int> line_values; // all values on this line
        while(iss >> value)           // extract like when reading an int from std::cin
            line_values.push_back(value); // put the value in the 1D (line) vector
        // check that all lines have the same amount of numbers
        if(return_value.size() && return_value[0].size()!=line_values.size())
            throw std::runtime_error("file format error");
        return_value.emplace_back(std::move(line_values)); // move this line's vector<int>
                                                           // to the result_value
    }
    return return_value;
}

int main() {
    if(std::ifstream is{"numbers.txt"}; is) {
        try {
            // auto arr2d = get_2d_array_of_ints_from_stream(is);
            // would be the same as:
            std::vector<std::vector<int>> arr2d = get_2d_array_of_ints_from_stream(is);
            std::cout << "Got a " << arr2d[0].size() << "x" << arr2d.size() << " array\n";
            for(const std::vector<int>& line_values : arr2d) {
                for(int value : line_values) {
                    std::cout << " " << value;
                }
                std::cout << "\n";
            }
            std::cout << "--\n";
            // or you can use the subscript style of arrays
            for(size_t y = 0; y < arr2d.size(); ++y) {
                for(size_t x = 0; x < arr2d[y].size(); ++x) {
                    std::cout << " " << arr2d[y][x];
                }
                std::cout << "\n";
            }
        } catch(const std::exception& ex) {
            std::cerr << "Exception: " << ex.what() << "\n";
        }
    }
}
0123456789

9012345678

8901234567

7890123456

67890123445

5678901234

4567890123

34567789012

2345678901

这是我到目前为止试过的,但看起来一团糟

  string array[30][30]; //row, column
  ifstream myfile("numbers.txt");

  int row = 0;
  int col = 0;
  while(!myfile.eof())
  {
      //Extract columns
      while(getline(myfile, array[row][col]),!'\n')
      {
         getline(myfile,array[row][col],' ');
        col++;
      }
    //Extract rows
    //    getline(myfile,array[row][col],'\n');

     //   row++;

        cout<<  row << '\t' <<  array[row][col] <<  "\n";
  }
字符串数组[30][30]//行、列
ifstream myfile(“numbers.txt”);
int行=0;
int col=0;
而(!myfile.eof())
{
//提取列
while(getline(myfile,数组[row][col]),!'\n')
{
getline(myfile,数组[row][col],“”);
col++;
}
//提取行
//getline(myfile,数组[row][col],'\n');
//行++;
cout
而(!myfile.eof())
很少是个好主意。当您读取最后一行时,该条件仍将计算为
true
eof()
仅在您尝试读取文件中最后一个字符之后才会设置。此外,
字符串数组[30][30]是一个不适合您的数据的硬编码30x30C样式数组。相反,使用C++容器<代码> STD::vector < /代码>(可以嵌套在您想要的多维尺寸中)动态地添加数字。
假设
numbers.txt
中没有空行,您可以这样做:

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <stdexcept>

std::vector<std::vector<int>> get_2d_array_of_ints_from_stream(std::istream& is) {
    std::vector<std::vector<int>> return_value;

    std::string line;
    while(std::getline(is, line)) {   // if this fails, EOF was found or there was an error
        std::istringstream iss(line); // put the line in a stringstream to extract numbers
        int value;                    // temporary used for extraction
        std::vector<int> line_values; // all values on this line
        while(iss >> value)           // extract like when reading an int from std::cin
            line_values.push_back(value); // put the value in the 1D (line) vector
        // check that all lines have the same amount of numbers
        if(return_value.size() && return_value[0].size()!=line_values.size())
            throw std::runtime_error("file format error");
        return_value.emplace_back(std::move(line_values)); // move this line's vector<int>
                                                           // to the result_value
    }
    return return_value;
}

int main() {
    if(std::ifstream is{"numbers.txt"}; is) {
        try {
            // auto arr2d = get_2d_array_of_ints_from_stream(is);
            // would be the same as:
            std::vector<std::vector<int>> arr2d = get_2d_array_of_ints_from_stream(is);
            std::cout << "Got a " << arr2d[0].size() << "x" << arr2d.size() << " array\n";
            for(const std::vector<int>& line_values : arr2d) {
                for(int value : line_values) {
                    std::cout << " " << value;
                }
                std::cout << "\n";
            }
            std::cout << "--\n";
            // or you can use the subscript style of arrays
            for(size_t y = 0; y < arr2d.size(); ++y) {
                for(size_t x = 0; x < arr2d[y].size(); ++x) {
                    std::cout << " " << arr2d[y][x];
                }
                std::cout << "\n";
            }
        } catch(const std::exception& ex) {
            std::cerr << "Exception: " << ex.what() << "\n";
        }
    }
}
#包括
#包括
#包括
#包括
#包括
std::vector从\u流(std::istream&is)中获取\u int\u的\u 2d\u数组{
std::向量返回值;
std::字符串行;
而(std::getline(is,line)){//如果失败,则找到EOF或出现错误
std::istringstream iss(line);//将该行放入stringstream以提取数字
int value;//临时用于提取
std::vector line_values;//此行上的所有值
while(iss>>value)//从std::cin读取int时提取like
line_values.push_back(value);//将值放入1D(line)向量中
//检查所有行是否具有相同数量的数字
if(返回值.size()&返回值[0].size()!=行值.size())
抛出std::runtime_错误(“文件格式错误”);
返回_值。将_放回(std::move(line_值));//移动此行的向量
//结果是_值
}
返回_值;
}
int main(){
if(std::ifstream为{“numbers.txt”};is){
试一试{
//auto arr2d=从_流(is)中获取_ints_的_2d_数组_;
//将与以下内容相同:
std::vector arr2d=从_流(is)获取_int的_2d_数组_;

std::我不能谢谢你,但我的作业要求我改用数组。我明白了。如果我知道这是作业,我的答案就不一样了。无论如何……你确定这是一个真正的限制吗?我希望这更像是一个建议。如果你读到关于你为什么改用数组的内容,你应该不会有任何问题。如果老师我会感到惊讶的是,r因为你用公司里每个人都用的东西来做这样的事情而不及格。