2016-11-19 100 views
0

我想從C++中使用fstream的文本文件中讀取多行二進制字符串。它目前正常工作,但字符串不能正常操作。我需要反轉字符串後,我從文件中讀取它們導致空終止符在錯誤的地方,並導致各種錯誤。是否有任何替代品'fstream'讀取數據到字符串或有任何方法我可以反向字符串從文件中讀入而不會與空終止符搞亂。替代使用fstream

繼承人我的代碼片段:

void Baby::getStore(string fileName, string* store){ 
    fstream myFile; 
    int i=0; 
    myFile.open(fileName.c_str(), ios::out | ios::in); 
    string currentLine; 
    if(myFile.is_open()){ 
     while(getline(myFile, currentLine)){ 
      store[i] = Baby::reverseString(currentLine); 
      for(int j=31; j>=0; j--){ 
       store[j] 
      } 
      i++; 
     } 
     myFile.close(); 
    }else{ 
     cout << "File not found\n"; 
    } 
} 

//reverses the string it is given 
string Baby::reverseString(string rev){ 
    string temp; 
    for(int i=rev.size(); i>0; i--){ 
     temp += rev[i-1]; 
    } 
    return temp; 
} 
+0

也許讀關鍵字'const'和u唱'std :: vector'和'std :: array' –

+1

你的問題不是'fstream'。這是你的'reverseString'函數被破壞了。這不是'fstream'的錯。目前還不清楚'j'周圍的內部循環應該做什麼。總的來說,你的代碼似乎通常被破壞 –

+1

你寫了一個錯誤的算法,與fstream真的沒有關係! – Klaus

回答

0

一種其他的方式來扭轉串不與空終止搞亂是std::reverse() function.Include算法頭文件,並替換此:

store[i] = Baby::reverseString(currentLine); 

與此:

std::reverse(currentLine.begin(),currentLine.end()); 
store[i] = currentLine; 
+1

謝謝!我起初使用這個,但我認爲這是造成的問題,所以我寫了我自己的,但現在修復它,它不是反向功能,讓我悲痛 – GavinHenderson5