2012-03-06 83 views
0

我正在编写一个C++控制台应用程序。在创建一个大小为(int)rowSize和columnSize的矩阵之后,我想将文本文件中的字母写入矩阵,但while循环从不运行,因为读者的位置是-1,我不能将它带到0.任何想法?seekg和tellg不兼容

void writeText2Vec(ifstream & reader, tmatrix<char> & table){ 
    string s; 
    int length, row = 0, column = 0; //beginning: column and 
            //row ids are set to 0. 
    reader.seekg(0); //reset the pointer to start 

    cout << reader.tellg(); // it results in -1. 
    while (getline(reader,s)){ 
     //for each line while loop occurs. 
     length = s.length(); 
     for(column = 0; column < length; column++) 
     { 
      table[row][column] = s.at(column); 
      //writing the letter to matrix. 
     } 
     row++; 
    } 

bool openFile(ifstream & reader, string filename){ 
    reader.open(filename.c_str()); 

    if (reader.fail()){ 
     exit("File cannot be found."); 
     return false; 
    } 
    else { 
     return true; 
    } 
} 

bool check(ifstream & reader, int & rowSize, int & columnSize){ 
    //checks for valid characters, if they are 
    //alphabetical or not and for the length. 

    string s; 
    int len = 0, max = 0; 
    while (getline(reader,s)){ 
     //runs for every line. 
     rowSize++; //calculation of row size 

     while (len < s.length()){ 
      if (!(isalpha(s.at(len)))){ 
       // Check to see if all characters are alphabetic. 
       exit("Matrix contains invalid characters!"); 
       return false; 
      } 
      len++; 
     } 
     if (max == 0){ 
      //if max is not set. 
      max = len; 
      len = 0; 
     } 
     else if (!(max == len)){ 
      //if they are different, then appropriate 
      //error message is returned. 
      exit("Matrix is not in a correct format!"); 
      return false; 
     } 
     else { 
      //else it resets. 
      len = 0; 
     } 
    } 
    rowSize -= 1; 
    columnSize = s.length(); //the last length is equal to column size 
    return true; 
} 
+1

'tellg()'的返回值'-1'表示失败,而不是位置。你可以发布'writeText2Vec()'的调用代码吗? – hmjd 2012-03-06 16:12:31

+0

改为尝试'reader.seekg(0,std :: ios :: beg)'。 – 2012-03-06 16:17:49

+0

尝试ios :: beg但没有改变结果。 tmatrix table(rowSize,columnSize); \t \t //创建矩阵表。 \t \t writeText2Vec(reader,table); \t \t //将txt文件写入矩阵。 – Yagiz 2012-03-06 16:24:24

回答

2

tellg()返回-1时发生了错误。当您调用该函数时,该流可能为错误状态 。如果您已经读取了 一次,那么出现输入失败,并且流为 处于错误状态,必须先清除该流,然后才能执行任何其他操作:reader.clear()

+0

谢谢你,它的工作原理 – Yagiz 2012-03-06 17:12:48