2016-11-19 107 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