ISSUE WITH C++ I/O CODE Below Is my code thus far, but I keep getting stuck in a
ID: 3795828 • Letter: I
Question
ISSUE WITH C++ I/O CODE
Below Is my code thus far, but I keep getting stuck in an infinite loop in my while loop. What's the issue? I created a conversionTest.cpp that just contains a main method with "<<< >>>>" in it to enter when prompted for a file. That's how I've been testing the code.
#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;
}
Explanation / Answer
Hi,
all of your code is correct .The only mistake and the reason why you are stuck in a infinite loop because of the while condition i.e "while (!inStream.eof())" .
Note: .inStream.eof() will only return true after reading the end of the stream but it doesn't indicate the next read will be the end of the stream.
So, conclusion is that you are just reading only time and checking the same data with condition endless time. So, you need to include another inStream.get(x); at the end of the while loop
modified loop :
inStream.get(x);
while (!inStream.eof()){
if (x == '<')
outStream << "<";
else if (x == '>')
outStream << ">";
else
outStream << x;
inStream.get(x); //now this code won't fix in infinite loop for the previous reason
}
cout << "end" << endl;
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.