0

I put file to cin stream via command argument like this:

./program < input.txt

And I have this simple code:

std::vector<std::string> getLines(std::istream& input)
{
    std::vector<std::string> data;
    std::string line;
    int i = 0;
    char c;
    while (input.get(c))
    {
        if (c == '\n')
        {
            data.push_back(line);
            i = 0;
        }
        else
            line += c;
    }
    return data;
}

int main(void)
{
    double elapsed;
    std::vector<std::string> out;

    Timer timer_1;
    // the data is now in cin stream so I pass it to function above
    out = getLines(std::cin);
    elapsed = timer_1.elapsed();

    for (unsigned int i = 0; i < out.size(); i++)
        std::cout << out[i] << '\n';
    std::cout << elapsed << '\n';

    // now try to stop program from closing:
    std::getchar();    // doesn't work
    system("pause");   // doesn't work either

    // this doesn't work too
    while (getchar() != '\n');
    getchar();

    // program exits before I can see the output
    return 0;
}

Of course I could just breakpoint the last statement but this cannot be done in release. If you are interested in Timer class I took it from this answer.

sanitizedUser
  • 1,456
  • 3
  • 14
  • 28
  • Why is this function included `std::vector getLines_usingLoop(std::istream& input)` ? please read [mcve] What is `getLines`? – Richard Critten Dec 22 '19 at 13:35
  • If you are invoking your program like this - `./program` - doesn't that mean you already have an external console that won't get closed on program exit? – Yksisarvinen Dec 22 '19 at 13:38
  • @RichardCritten Sorry I tried to shorten the name in main function and forgot to do it in definition. – sanitizedUser Dec 22 '19 at 13:38
  • @Yksisarvinen I am invoking it in VS2019, the command argument is selected in project properties. – sanitizedUser Dec 22 '19 at 13:38
  • In general, your problem seems to be that input stream has EOF bit set, therefore all your getchars immidiately fail.But I don't know how to use VS or why `system("pause");` is not working. – Yksisarvinen Dec 22 '19 at 13:42
  • How is `cin` reaching `eof`? `Ctrl + c`? This will abort the program, it won’t insert an `eof`. – zdf Dec 22 '19 at 14:01
  • Also, `getchar` will fail if you already reached `eof`. – zdf Dec 22 '19 at 14:08
  • @TheFailurebyDesign `cin` reaches eof because it's redirected to read from a file, and that file is of a finite size. – Igor Tandetnik Dec 22 '19 at 15:04
  • @IgorTandetnik Right. Missed it. – zdf Dec 22 '19 at 15:40

0 Answers0