0

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?

SevenDays
  • 3,718
  • 10
  • 44
  • 71

3 Answers3

4

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 :)

anatolyg
  • 26,506
  • 9
  • 60
  • 134
1

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)

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
0

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.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • I need to run the program by double-clicking, and outputs the data to the console.But my program immediately disappear after output data. – SevenDays Oct 27 '11 at 16:51