如何从文本文件中间读取

时间:2014-05-10 00:44:17

标签: c++ file-io fstream

我正在编写一个从两个文件(“joke.text”和“punchline.txt”)读取的程序,在punchline文件中有“垃圾”,我无法弄清楚如何只阅读我想要的行。请帮忙。另外,我正在使用Visual Studios

这就是我所拥有的:

   #include <iostream>
   #include <fstream>
   #include <string>
   using namespace std;

int main()
{
    fstream jokeFile;
    string data;
    char input;
    cout << "opening the file... \n";
    jokeFile.open("joke.txt", ios::in);

    if (jokeFile.is_open())
    {
        getline(jokeFile, data);

        while (jokeFile )
        {
            cout << data <<endl;
            getline(jokeFile, data);
        }

        jokeFile.close();

    } 
    else
    {
        cout << "ERROR: could not open that file\n";
    }


    cout << "would like you see the punchline? (Y/N) \n";
    cin >> input;

/*  if ( input == 'N' || 'n')
    {
        cout << "Ok, keep guessing\n";


    }*/

     if (input == 'Y' || 'y')
    {

        jokeFile.open("punchline.txt", ios::in);

        if (jokeFile.is_open())
        {
            //getline(jokeFile, data, '\n');

            while (jokeFile)
            {

                cout << data; 
                getline(jokeFile, data, '\n');

            }

            jokeFile.close();
        }

        else
        {

            cout << "ERROR: could not open the file\n";
        }
    }


    /*{
        cout << "invalid response, try again\n";
    }*/




    system("pause");
    return 0;
}

这是输出:

opening the file... 
Two men who work together in a facory were talking.
"I know how to get some time off," said one.
"How are you going to do that?" asked the other.
"Watch," he said, and climbed a ladder to the ceiling.
The foreman asked what he was doing up there,
and the man replied. "I'm a lightbulb."
"I think you need some time off," the foreman
said, and the first man walked out of the 
factory. After a moment, the second man followed 
him. "Where do you think you're going?" 
the foreman shouted.


would like you see the punchline? (Y/N) 
y
asdasdasdasdasdfdssdfdsaasdfdssfddsfdsasdsad"I can't work in the dark, " he said.

3 个答案:

答案 0 :(得分:1)

您可以使用fseek来获取文件的大小,而不是将其除以一半,然后再次使用fseek读取一半。

int fseek(FILE *stream, long int offset, int whence)

示例:(尚未经过测试)

int size = fseek(jokeFile, 0, SEEK_END);
fseek(jokeFile, size/2.0, SEEK_SET);

答案 1 :(得分:0)

有两种可能性:

  1. 知道您希望寻找的位置。如果是,请在此处查看搜索功能:http://www.cplusplus.com/reference/istream/istream/seekg/

  2. 知道您希望寻找的位置,但您知道垃圾&#34;看起来像什么&#34;,在这种情况下您需要阅读并解析它,直到你读完它为止。

答案 2 :(得分:0)

我认为你的问题误导了你所提出的问题。看起来你的程序试图输出所有的jokefile.txt,提示用户,然后输出所有的punchline.txt文件。在打孔线之前的垃圾输出必须是返回到“数据”的数字&#39;在jokefile.txt上达到EOF时的字符串。你第一次读的punchline.txt被注释掉了,所以那个循环中的cout在读取和输出妙语之前就会转储垃圾。