【发布时间】:2016-06-30 02:13:03
【问题描述】:
我似乎无法让程序调用第二个函数。该程序应该打开一个笑话文件,读取它并为用户显示它。然后关闭文件,打开第二个妙语文件,查找最后一行并将其读给用户。我让它打开第一个文件并显示笑话,但在那之后它什么也没做。知道我做错了什么吗?先感谢您。
#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
}
【问题讨论】:
-
你不能“似乎”让程序调用第二个函数?这只是一个猜测。您应该使用调试器并找出它是否调用该函数。 (我认为确实如此,但该功能并没有按照您的想法做 - 正如给出的答案所示。)
标签: c++