这是我已经编写的代码,但是我希望能够将for循环输出保存到文件中。我尝试使用不同的方法,例如在循环外和循环内在循环周围使用ofstream。但是,即使使用这些代码运行我的代码,它也不会像我想要的那样向文件输出信息。
#include <iostream>
#include <fstream>
using namespace std;
struct MyStruct {
int number;
int numbertwo;
};
void printStruct(MyStruct thestruct);
int main(){
MyStruct alex[4] = {{15, 20},{30, 35},{45, 50},{60, 65}};
cout<<"Number"<<"\t"<<"Numbertwo"<<endl;
int sizeofarray = 4;
for(int x = 0; x < sizeofarray; x = x+1){
printStruct(alex[x]);
}
}
void printStruct(MyStruct thestruct){
for(int x = 0;x < 1; x++)
if(thestruct.number > 30){
cout<<thestruct.number*10<<"\t"<<thestruct.numbertwo<<endl;}
else if(thestruct.number <= 30){
cout<<thestruct.number*10<<"\t"<<thestruct.numbertwo<<endl;
}
答案 0 :(得分:0)
如果将流参数添加到打印功能,则可以选择它的位置。
void printStruct(ostream& os, const MyStruct& thestruct);
int main(){
MyStruct alex[4] = {{15, 20},{30, 35},{45, 50},{60, 65}};
int sizeofarray = 4;
// Print to a file
ofstream output("results.txt");
output << "Number" << "\t" << "Numbertwo" << endl;
for(int x = 0; x < sizeofarray; x = x+1){
printStruct(output, alex[x]);
}
// Print the same to stdout
cout << "Number" << "\t" << "Numbertwo" << endl;
for(int x = 0; x < sizeofarray; x = x+1){
printStruct(cout, alex[x]);
}
}
void printStruct(ostream& os, const MyStruct& thestruct){
if(thestruct.number > 30){
os << thestruct.number*10 << "\t" << thestruct.numbertwo << endl;
else
os << thestruct.number*10 << "\t" << thestruct.numbertwo << endl;
}