Frage

See below in comment.

int main(){
    //freopen("input.txt","r",stdin);//if I uncomment this line the console will appear and disappear immediately
    int x;
    cin>>x;
    cout<<x<<endl;
    system("pause");
    return 0;
}

How to make it work?

War es hilfreich?

Lösung

Solution 1: use cin.ignore instead of system:

...
cout<<x<<endl;
cin.ignore(1, '\n'); // eats the enter key pressed after the number input
cin.ignore(1, '\n'); // now waits for another enter key
...

Solution 2: if you are using MS Visual Studio, press Ctrl+F5

Solution 3: reopen con (will only work on Windows, seems your case)

...
cout<<x<<endl;
freopen("con","r",stdin);
system("pause");
...

If you use solution 3, don't forget to add comments on what the code is doing and why :)

Andere Tipps

Use std::ifstream instead of redirecting stdin:

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream fin("input.txt");
    if (fin)
    {
        fin >> x;
        std::cout  << x << std::endl;
    }
    else
    {
        std::cerr << "Couldn't open input file!" << std::endl;
    }

    std::cin.ignore(1, '\n'); // waits the user to hit the enter key
}

(Borrowed the cin.ignore trick from anatolyg's answer)

You use freopen to change your program's standard input. Any program you start inherits your program's standard input, including the pause program. The pause program reads some input from input.txt and terminates.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top