函数中的fstream

问题描述

我无法从tilstart函数中的文件提取任何内容,但是该程序没有任何问题。该功能的目标是遍历txt文件,直到它“开始”为止。我必须使用递归,但是我必须在函数的末尾(//)tilstart(files)以防止堆栈溢出,因为文件未提供输入。 cout

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

void tilstart(ifstream& file)
{
    //ifstream files(file);
    string start;

    file >> start;

    cout << start;

    if (start == "start") {

        cout << start;
        return;
    }

    cout << start;

    // tilstart(file);
}

int main()
{

    ifstream files("input13.txt");
    files.open("input13.txt");

    if (files.is_open()) {

        tilstart(files);
    }

    return 0;
}    

这是文件vvv。

going
there
start
h
f
t

解决方法

我建议您在扫描文件时使用getlinehttp://www.cplusplus.com/reference/string/string/getline/

另请参阅: How to read until EOF from cin in C++

,

递归是一种功能强大的分析工具,但很少是一种合适的实现技术。编写循环:

void tilstart(std::ifstream& file) {
    std::string start;
    while (file >> start) {
        if (start == "start")
            break;
        }
}
,

谢谢你们的贴士!我发现我之所以没有从文件中获取输入,是因为主要是我忘了编辑第二行之后才编辑第一行。

ifstream files("input13.txt");
files.open("input13.txt");

我做了一次:

ifstream files;
files.open("input13.txt");

成功了!如果有人能告诉我为什么这就是我将不胜感激的原因:)