【问题标题】:Program seems to be skipping function call程序似乎正在跳过函数调用
【发布时间】: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++


【解决方案1】:

seekg 在文件中获取一个偏移量 - 您正在传递它 '/n' 这不是一个偏移量。

因为您使用了正斜杠 (/),而不是反斜杠 (\),所以编译器将 '/n' 视为 Unicode 或多字节字符序列并向前移动 12142 个字节(至少在 VS 2013 中) ),这可能超出了文件的末尾。

您的评论还说“快进到文件末尾”,但您使用的是文件开头的ios:beg

【讨论】:

    【解决方案2】:
    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 了解一种可能的算法来查找文件中的最后一行。

    【讨论】:

    • 谢谢。虽然您的帖子没有帮助解决我的主要问题,但您推荐给我的帖子确实解决了我的主要问题。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多