C ++中的inData.open和inData.close

问题描述 投票:1回答:1

我发现添加一段时间的正确方法,所以我可以完成这个练习。但是,有两件事需要触摸。文件输出显示两次。第一次正确,第二次在一行(我不需要这一行显示)。第二个问题是account ++函数。它必须显示7个单词的计数,但它的计数为8。为什么?你能帮帮我吗?问题出在最后一刻。

 #include<iostream>
    #include<fstream>//step#1
    #include<string>

    using namespace std;
    int main()

    {

        string word, fileName;
        int charcounter = 0, wordcounter = 0;
        char character;

        ifstream inData;// incoming file stream variable

        cout << " Enter filename or type quit to exit: ";
        cin >> fileName;



        //loop to allow for multiple files data reads
        while (fileName != "quit")

        {
            inData.open(fileName.c_str());//open file and bind file to ifstream variable

        //loop for file not found validation
            while (!inData)//filestream is in fail state due to no file
            {
                inData.clear();//clear the fail state 
                cout << "File not found. Enter the correct filename: ";
                cin >> fileName;
                inData.open(fileName.c_str());
            }


            inData >> character;//extract a single character from the file
            cout << "\n*****************************\n";
            while (inData)


            {
                cout << character;
                inData.get(character);//extract the next character and the next character
                charcounter++;

            }
    //Here is the loop that is missing something
    //I was told to close the file 

            inData.close();

    //open up the file again and add the while loop

            inData.open(fileName.c_str());

            while (inData)

            {

                cout << word;
                inData >> word;//extract the next word and the next word
                wordcounter++;
            }



            cout << "\n******************************\n";
            cout << fileName << " has " << wordcounter << " words" << endl;
            inData.close();//close the ifstream conection to the data file


            charcounter = 0; //reset char and word counts
            wordcounter = 0;
                //port for next file or exit
            cout << "Enter a filename or type quit to exit: ";
            cin >> fileName;

        }

        return 0;

    }
c++
1个回答
0
投票

您获得冗余输出的原因是您输出文件的内容两次,例如

第39-43行

        while (inData)


        {
            cout << character;
            ...

第57-61行

        while (inData)

        {

            cout << word;
            ...

无论是逐字符输出还是逐字输出,都要输出文件的内容。在一个循环中逐个字符地执行它,然后在另一个循环中逐个字符地执行它会导致输出的两倍。

此外,不需要循环文件两次来计算字符然后单词 - 在一个循环中完成所有操作,例如

        int charcounter = 0,
            wordcounter = 0,
            inword = 0;         /* flag indicating reading chars in word */
        ...
        while (inData.get(character)) { /* read each character in file */
            if (isspace (character))    /* if character is whitespace */
                inword = 0;             /* set inword flag zero */
            else {                      /* if non-whitespace */
                if (!inword)            /* if not already in word */
                    wordcounter++;      /* increment wordcounter */
                inword = 1;             /* set inword flag 1 */
            }
            charcounter++;              /* increment charcounter */
        }

您遇到的其余问题仅仅是由于您尝试使用的混乱循环逻辑,能够打开不同的文件,直到用户键入"quit"。您只需要一个外循环,它将不断循环,直到用户键入"quit"。您不需要对文件名进行多次检查和多次提示。只需使用一个循环,例如

    for (;;) {      /* loop continually until "quit" entered as fileName */
        string word, fileName;  /* fileName, character, inData are */
        char character;         /* only needed within loop */
        int charcounter = 0,
            wordcounter = 0,
            inword = 0;         /* flag indicating reading chars in word */
        ifstream inData;

        cout << "\nEnter filename or type quit to exit: ";
        if (!(cin >> fileName)) {       /* validate every read */
            cerr << "(error: fileName)\n";
            return 1;
        }
        if (fileName == "quit")         /* test for quit */
            return 0;

        inData.open (fileName);         /* no need for .c_str() */
        if (!inData.is_open()) {        /* validate file is open */
            cerr << "error: unable to open " << fileName << '\n';
            continue;
        }
        ...  /* the read loop goes here */
        inData.close();   /* closing is fine, but will close at loop end */

        cout << '\n' << fileName << " has " << wordcounter << " words and " 
            << charcounter << " characters\n";
    }

进行这些更改可以清理程序流程并使循环逻辑变为直接。总而言之,你可以做到:

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>

using namespace std;

int main (void) {

    for (;;) {      /* loop continually until "quit" entered as fileName */
        string word, fileName;  /* fileName, character, inData are */
        char character;         /* only needed within loop */
        int charcounter = 0,
            wordcounter = 0,
            inword = 0;         /* flag indicating reading chars in word */
        ifstream inData;

        cout << "\nEnter filename or type quit to exit: ";
        if (!(cin >> fileName)) {       /* validate every read */
            cerr << "(error: fileName)\n";
            return 1;
        }
        if (fileName == "quit")         /* test for quit */
            return 0;

        inData.open (fileName);         /* no need for .c_str() */
        if (!inData.is_open()) {        /* validate file is open */
            cerr << "error: unable to open " << fileName << '\n';
            continue;
        }

        while (inData.get(character)) { /* read each character in file */
            if (isspace (character))    /* if character is whitespace */
                inword = 0;             /* set inword flag zero */
            else {                      /* if non-whitespace */
                if (!inword)            /* if not already in word */
                    wordcounter++;      /* increment wordcounter */
                inword = 1;             /* set inword flag 1 */
            }
            charcounter++;              /* increment charcounter */
        }
        inData.close();   /* closing is fine, but will close at loop end */

        cout << '\n' << fileName << " has " << wordcounter << " words and " 
            << charcounter << " characters\n";
    }
}

示例输入文件

$ cat ../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

示例使用/输出

$ ./bin/char_word_count

Enter filename or type quit to exit: ../dat/captnjack.txt

../dat/captnjack.txt has 16 words and 76 characters

Enter filename or type quit to exit: quit

wc确认

$ wc ../dat/captnjack.txt
 4 16 76 ../dat/captnjack.txt

仔细看看,如果您有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.