2016-06-30 4 views
-1

2番目の関数を呼び出すプログラムを取得できないようです。プログラムはジョークファイルを開き、それを読んでユーザに表示することになっています。その後、ファイルを閉じて、2番目のパンチラインファイルを開き、最後の行を探してユーザーにそれを読んでください。最初のファイルを開いてジョークを表示するようになっていますが、それ以降は何もしません。私が間違っていることは何か考えていますか?前もって感謝します。プログラムが関数呼び出しをスキップしているようです

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

// Function prototypes 
void displayAllLines(ifstream &joke); // Display joke 
void displayLastLine(ifstream &punchline); // Display punchline 

int main() 
{ 
    ifstream jokeFile, punchLineFile; 

    // Open the joke file 
    jokeFile.open("joke.txt", ios::in); 

    // Make sure the file actually opens 
    if (!jokeFile) 
     cout << "Error opening file." << endl; 

    // Call on function to display the joke 
    displayAllLines(jokeFile); 

    // Close the joke file 
    jokeFile.close(); 

    // Open the punchline file 
    punchLineFile.open("punchline.txt", ios::in); 

    // Make sure the file actually opens 
    if (!punchLineFile) 
     cout << "Error obtaining the punchline, sorry :(." << endl; 

    // Call on function to display punchline 
    displayLastLine(punchLineFile); 

    // Close the punchline file 
    punchLineFile.close(); 

    system("pause"); 
    return 0; 
} 

// function to display the joke 
void displayAllLines(ifstream &joke) 
{ 
    string input; 

    // Read an item from the file 
    getline(joke, input); 

    // Display the joke to the user 
    while (joke) 
    { 
     cout << input << endl; 
     getline(joke, input); 
    } 
} 

// function to display the punchline 
void displayLastLine(ifstream &punchline) 
{ 
    string input; 

    punchline.seekg(0L, ios::beg); // Fast forward to the end of the file 
    punchline.seekg('/n', ios::cur); // rewind the the new line character 

    getline(punchline, input); // Read the line 
    cout << input << endl; // display the line 

} 
+0

プログラムに2番目の関数を呼び出すように見えることはできませんか?それはちょうど推測です。関数を呼び出すかどうかにかかわらず、デバッガを使用して*見つけ出す必要があります。 (私はそうしていると思うが、その機能はあなたの考えをしない - 与えられた答えが示す通り) – AAT

答えて

0
punchline.seekg(0L, ios::beg); // Fast forward to the end of the file 

いいえ、それはしていません。これはファイルの先頭に早送りされます。これが "ios :: beg"の意味です。

punchline.seekg('/n', ios::cur); // rewind the the new line character 

これは、改行文字にもかかわらず、巻き戻しません。最初の改行文字に巻き戻されず、最後の改行文字に巻き戻されません。 seekg()は、指定されたとおり、常にgetポインタを固定オフセットに配置します。ここで、固定オフセットはまったく無意味です。

コンパイラがこの行について不平を言っている可能性があります。コンパイラの苦情を無視しないでください。ただし、コンパイラがコンパイルしているにもかかわらず、コンパイラの苦情はまだコンパイルされています。

this questionを参照してください。ファイル内の最後の行を見つけるアルゴリズムが1つあります。

+0

ありがとう。あなたの投稿は私の主な問題を解決するのに役立たなかったが、あなたが私に言いました投稿。 :) –

1

seekgは、ファイル内でオフセットをとります。オフセットではない'/n'を渡しています。おそらくあなたは、スラッシュ(/)ではなく、バックスラッシュ(\)を使用しているため、コンパイラは、Unicodeまたはマルチバイト文字列として'/n'を処理し、前方(少なくともVS 2013年)12142のバイトを移動さ

、あなたのファイルの最後を過ぎてください。

あなたのコメントは「ファイルの最後まで早送りしますが、ファイルの先頭にあるios:begを使用しています。

関連する問題