2014-05-10 16 views
1

我正在編寫一個從兩個文件(「joke.text」和「punchline.txt」)中讀取的程序,在punchline文件中有「垃圾」,我無法弄清楚如何只讀我想要的行。請幫忙。另外,我使用視覺工作室如何從文本文件的中間讀取

這是我有:

#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. 
+1

程序如何知道它想要哪一行? (或者應該怎麼知道?) – immibis

+0

如果你確切地知道你想讀的是哪行,你可以調用'fseek()',它將把文件指針改爲你想要的行。之後,你可以調用'getline()' – Elias

回答

0

有兩種可能性:

  1. 知道你想尋求的位置。如果是這樣,那麼看到這裏的查找功能:http://www.cplusplus.com/reference/istream/istream/seekg/

  2. 知道你想尋求的位置,但你知道什麼是垃圾「的模樣」,在這種情況下,你需要閱讀它解析它,直到你讀過它。

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); 
0

我認爲你的問題會誤導你呈現的問題。它看起來像你的程序試圖輸出所有的jokefile.txt,提示用戶,然後輸出所有的punchline.txt文件。當在jokefile.txt上達到EOF時,在衝線之前的垃圾輸出必須是返回到'data'字符串的亂碼。你的第一個閱讀punchline.txt被註釋掉了,所以在這個循環中的cout在閱讀和輸出punchline之前就會轉儲垃圾。