【问题标题】:Reading integers from file and initializing a multidimensional array从文件中读取整数并初始化多维数组
【发布时间】:2017-04-04 00:06:22
【问题描述】:

所以我有这段代码,它读取一个特定文件,该文件分别具有值 22 和 14,并且位于同一行。

int main()
{
    int rows = 0;
    int column = 0;

    string line;
    ifstream file("Path To File"); 
    if(file.is_open()){ 
            getline(file, line);
            cout << line << endl;
        file.close();
    }
    else{ 
        cout << "File cannot be read." << endl;
        cin.get();
        return 0;
    }
}

如何创建一个多维数组,其大小与我从文件中读取的整数一样大?

例如,如果文件有 22 和 10,则行数应 = 22,列数应 = 10。

【问题讨论】:

    标签: c++ arrays multidimensional-array


    【解决方案1】:

    从蛮力开始并根据需要调整性能。

    Loop while std::getline can read a line from the file
        Write the line into a std::stringstream. 
        Make an empty std::vector. 
        Loop while >> can read a token from the std::stringstream
            Push the token into the std::vector. 
        Push the std::vector into a std::vector of std::vectors. 
    

    如果矩阵中的行太短,您可能必须用零填充它们。

    【讨论】:

      【解决方案2】:

      假设输入文件只包含由空格分隔的 row 和 col 值,您可以使用 stringstream 将行一次一个单词流式传输到 int。

      int rows, column;
      std::string line;
      std::ifstream file("Path To File"); 
      if(file.is_open()){ 
          std::getline(file, line);
          std::cout << line << std::endl;
          std::stringstream( line ) >> rows >> column;
          file.close();
      }
      int matrix[ rows][ column ];
      

      编辑为使用 std::stringstream 而不是 std::stoi

      【讨论】:

      • 我是否需要#include 某些内容才能使用 std::stoi?
      • stoi 是在 C++11 中引入的。如果您的编译器不支持使用 std::atoi( word.c_str() )
      • 嗯,很奇怪。如果我使用它会显示“错误:'stoi' 未在此范围内声明”或“错误:'atoi' 未在此范围内声明”
      • 需要#include 字符串。否则 #include 然后 std::stringstream( word ) >> rows;一个快速的谷歌将提供许多将字符串转换为 int 的方法
      • 好吧,我设法让它工作了。所以它应该看起来像这样?它编译没有错误。 if(file.is_open()){ getline(file, linea); cout >编号;字符串流(数字)>>行;文件>>编号;字符串流(数字)>>列;文件.close();整数矩阵[行][列];文件.close(); }
      猜你喜欢
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 2011-04-03
      • 2015-07-20
      相关资源
      最近更新 更多