【发布时间】:2017-02-21 02:01:52
【问题描述】:
我正在编写一个读取 C++ 源文件并将所有“”符号转换为“>”的代码。我写出了 main 方法,一切都编译得很好,但是现在我实际上是在程序顶部写出我的 convert 函数,我陷入了一个无限循环,我正在撞墙,罪魁祸首是什么。有人可以帮我吗? 我包含了整个程序,以防问题出在我的 I/O 编码上,但我用斜杠包围了函数。希望我不会被喷。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
//FUNCTION GOES THROUGH EACH CHARACTER OF FILE
//AND CONVERTS ALL < & > TO < or > RESPECTIVELY
//////////////THIS IS THE FUNCTION IN QUESTION//////////
void convert (ifstream& inStream, ofstream& outStream){
cout << "start" << endl;
char x;
inStream.get(x);
while (!inStream.eof()){
if (x == '<')
outStream << "<";
else if (x == '>')
outStream << ">";
else
outStream << x;
}
cout << "end" << endl;
};
///////////////////////////////////////////////////////////////////////////
int main(){
//FILE OBJECTS
ifstream inputStream;
ofstream outputStream;
string fileName;
//string outFile;
//USER PROMPT FOR NAME OF FILE
cout << "Please enter the name of the file to be converted: " << endl;
cin >> fileName;
//outFile = fileName + ".html";
//ASSOCIATES FILE OBJECTS WITH FILES
inputStream.open(fileName.c_str());
outputStream.open(fileName + ".html");
//CREATES A CONVERTED OUTPUT WITH <PRE> AT START AND </PRE> AT END
outputStream << " <PRE>" << endl;
convert(inputStream, outputStream);
outputStream << " </PRE>" << endl;
inputStream.close();
outputStream.close();
cout << "Conversion complete." << endl;
return 0;
}
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
这里的bug太多了。从 ol-reliable
while !feof错误开始,到神秘循环结束,它神奇地期望某个变量在循环中的某处无缘无故地改变其值... -
在从不读取文件的循环中很难到达文件末尾。
-
尝试在循环中再次调用 get。
-
尝试做例如
while (inStream >> x)代替。