2014-04-15 122 views
1

對您而言似乎很容易,但我被困在這裏。這是C++中用於從ASCII文件加載矩陣的函數。無法將'const char *'轉換爲'std :: istream *

void load_matrix(std::istream* is, 
     std::vector< std::vector<double> >* matrix, 
     const std::string& delim = " \t") 
{ 
    using namespace std; 

    string  line; 
    string  strnum; 

    // clear first 
    matrix->clear(); 

    // parse line by line 
    while (getline(*is, line)) 
    { 
     matrix->push_back(vector<double>()); 

     for (string::const_iterator i = line.begin(); i != line.end(); ++ i) 
     { 
      // If we i is not a delim, then append it to strnum 
      if (delim.find(*i) == string::npos) 
      { 
       strnum += *i; 
       continue; 
      } 

      // if strnum is still empty, it means the previous char is also a 
      // delim (several delims appear together). Ignore this char. 
      if (strnum.empty()) 
       continue; 

      // If we reach here, we got a number. Convert it to double. 
      double  number; 

      istringstream(strnum) >> number; 
      matrix->back().push_back(number); 

      strnum.clear(); 
     } 
    } 
} 

在我的代碼,我們得到的文件名從用戶如下有default.dat文件availble的

const char* filename1 = (argc > 1) ? argv[1] : "default.dat"; 

我想知道我怎麼可以使用這個文件名1爲argunemt FOT負載矩陣功能。

感謝

+0

有什麼問題[ 'ifstream的:: open'(http://www.cplusplus.com/reference/fstream/ifstream/open/)? – Till

回答

5

構造帶文件名的std::ifstream對象,然後將指針傳遞給該對象到您的loadmatrix功能:std::ifstream繼承std::istream,所以這個typechecks:

std::vector< std::vector<double> > matrix; 
std::ifstream f(filename1); 
if (!f) { 
    // XXX Error handling 
} 
loadmatrix(&f, &matrix); 
+0

感謝您的回覆。你是對的.... –

相關問題