I/O程序卡在循环C 中

I/O program stuck in loop C++

本文关键字:循环 程序      更新时间:2023-10-16

我正在研究一个代码,该代码在C 源文件中读取,并将所有'<'符号转换为"<"以及">"的所有">"符号。我写出了主要方法,所有内容都很好地编译了,但是现在我实际上在程序的顶部写下了转换函数,我陷入了无限的循环中,并且我对罪魁祸首的是一堵墙。有人可以帮我吗?我包括整个程序,以防问题在我的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 &lt; or &gt; 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 << "&lt;";
        else if (x == '>')
            outStream << "&gt;";
        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;
}

在阅读文件时,操纵文件不是一个好方法。正确的方法是,首先read整个文件,store数据,manipulate存储的数据,然后 update文件。希望此代码对您有所帮助:)

   void convert()
    {
        int countLines = 0; // To count total lines in file
        string *lines; // To store all lines
        string temp;
        ifstream in; 
        ofstream out;
        // Opening file to count Lines
        in.open("filename.txt");
        while (!in.eof())
        {
            getline(in, temp);
            countLines++;
        }
        in.close();
        // Allocating Memory
        lines = new string[countLines];
        // Open it again to stroe data
        in.open("filename.txt");
        int i = 0;
        while (!in.eof())
        {
            getline(in, lines[i]);
            // To check if there is '<' symbol in the following line
            for (int j = 0; lines[i][j] != ''; j++)
            {
                // Checking the conditon
                if (lines[i][j] == '<')
                    lines[i][j] = '>';
            }
            i++;
        }
        in.close();
        // Now mainuplating the file
        out.open("filename.txt");
        for (int i = 0; i < countLines; i++)
        {
            out << lines[i];
            if (i < countLines - 1)
                out << endl;
        }
        out.close();
    }