#include<iostream>
using namespace std;
int main ()
{
int x;
cout << "Pls. enter a natural number" << "\n" ;
cin >> x ;
cout << "\n" ;
for (int i=1 ; i<=x ; i++ )
{
x = x-1;
cout << i << " " << x << "\n" ;
}
cout << "\n" ;
system ("pause");
return 0;
} $
我有这个示例代码,首先是cin然后cout ..我的问题是,而不是在cmd中输出的cout它将被发送到.txt文件..我将在哪里包含fstream代码..谢谢很多...
答案 0 :(得分:1)
使用<fstream>
:
#include <fstream>
// ...
std::ofstream ofs("output.txt");
ofs << "You said, " << n << "\n";
如果您将打印代码考虑在内,则可以使用文件或iostream:
void print(std::ostream & o, int n) { o << "You said, " << n << "\n"; }
int main()
{
int n = 11;
std::ofstream ofs("output.txt");
print(std::cout, n);
print(ofs, n);
}
答案 1 :(得分:0)
这是在file.txt中编写的简单示例:
不要忘记包含 fstream 标题。
ofstream file;
file.open("c://file.txt",ios::out);
file << "Hello, this is test text.";
file.close();
关于你的例子,请参阅下面的代码
ofstream file;
file.open("c://file.txt",ios::out);
int x;
cout << "Pls. enter a natural number" << "\n" ;
cin >> x ;
cout << "\n" ;
for (int i=1 ; i<=x ; i++ )
{
x = x-1;
file << i << " " << x << "\n" ;
}
file << "\n" ;
file.close();
system ("pause");
}
结果:
如果输入5,结果将在文件中:
1 4
2 3
3 2