以下のコメントを参照してください。
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;
}
それを機能させる方法は?
以下のコメントを参照してください。
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;
}
それを機能させる方法は?
解決策 1:cin.ignore
の代わりに使用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
...
解決策 2: MS Visual Studio を使用している場合は、Ctrl+F5 を押します。
解決策 3: 再度開くcon
(Windows でのみ機能します。あなたのケースのようです)
...
cout<<x<<endl;
freopen("con","r",stdin);
system("pause");
...
解決策 3 を使用する場合は、コードの動作とその理由についてコメントを追加することを忘れないでください:)
std::ifstream
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
}
(cin.ignore
anatolygの答えからトリックを借りました)