2014-09-10 77 views
0

我在努力超载ifstream操作符以矩阵形式从文件获取输入并创建一个2D数组。这是一个3x3矩阵。这是一项任务的一小部分,没有它我的整个任务是毫无意义的。如何使用ifstream将文件输入到2D数组中?

文件例如:

1 2 3 
4 5 6 
7 8 6 
+0

对不起文件例子应该是一个3x3矩阵 – newProgrammerOnTheBlock 2014-09-10 19:05:52

+1

请告诉我们你第一次尝试的东西。 – 0x499602D2 2014-09-10 19:05:56

+0

我同意。这太简单了;看来你没有做任何测试,或者你已经发现了如何阅读。 – 2014-09-10 19:17:27

回答

0

我做过这样...

#include <iostream> 
#include <fstream> 
#include <string> 
#include <sstream> 

using namespace std; 

int main() 
{ 
    int data[3][3]; 
    int i = 0; 
    int j = 0; 
    ifstream in(filename); 
    std::string line; 
    std::string temp; 
    while(std::getline(in, line)) 
    { 
     std::istringstream iss(line); 

     // Parse each line using the input string stream 
     j = 0; 
     while(std::getline(iss,temp,' ')) 
     { 
     data[i][j] = std::stoi(temp); 
     j++; 
     } 
     i++; 
    } 
    return 0; 
} 
相关问题