0

i cannot extract anything from the file in the tilstart function but the program finishes with no issues. The goal of the function is to go through the txt file until it gets to "start". I have to use recursion but i had to (//)tilstart(files) in the end of the function to prevent stack overflow since the file wasn't giving an input. the cout << start was so i can see if the program was picking up word.

#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;
}    

this is the filevvv.

going
there
start
h
f
t
drescherjm
  • 10,365
  • 5
  • 44
  • 64

3 Answers3

0

I suggest you use getline when scanning the file: http://www.cplusplus.com/reference/string/string/getline/

Also see: How to read until EOF from cin in C++

Den-Jason
  • 2,395
  • 1
  • 22
  • 17
  • i tried using getline but the string start keeps coming up empty. –  Aug 29 '20 at 20:53
  • You need the getline in a loop. Look at the examples in the linked thread. You program needs to read line-by-line until it reaches the end-of-file. – Den-Jason Aug 29 '20 at 20:54
0

Recursion is a powerful analytical tool, but it is only rarely an appropriate implementation technique. Write a loop:

void tilstart(std::ifstream& file) {
    std::string start;
    while (file >> start) {
        if (start == "start")
            break;
        }
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

thank you for yalls tips! i found out the reason i wasnt getting an input from the file was because in main i forgot to edit the first line after i made the second line.

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

once i did:

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

it worked! if anyone could tell me why this was the reason i would greatly appreciate :)

  • Attempting to open a stream that is already open sets (I think) the `fail` bit so subsequent reads will fail. – Paul Sanders Aug 29 '20 at 21:15
  • In the first version, remove the second line. That’s a better approach Than the second version. Construct objects with meaningful values rather than default initializing them and immediately overwriting the default values. – Pete Becker Aug 29 '20 at 21:47