【问题标题】:How would I save the output of this forloop我将如何保存这个 for 循环的输出
【发布时间】:2018-08-29 22:51:05
【问题描述】:

这是我已经编写的代码,但我希望能够将我的 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;

}

【问题讨论】:

  • 实例化流 fout; call fout.open('file.ext"); 使用 fout 代替 cout。完成后,调用 fout.close()
  • 你能打印“Hello, world!”吗?到一个文件?
  • 是的,我可以将 hello world 打印到我刚刚卡住的文件中,因为 for 循环从未这样做过
  • 这不是编译。我找不到alexisgay的定义。
  • 很高兴你很高兴并想把这件事告诉全世界,但考虑到其他人可能不会像你一样使用老式的词也很好。

标签: c++ file


【解决方案1】:

如果您向打印函数添加流参数,您可以选择它的去向。

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;
}

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 1970-01-01
    • 2017-07-14
    • 2010-12-13
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多