【发布时间】:2016-05-23 02:04:19
【问题描述】:
我必须创建一个简单的代码,它应该创建一个 .txt 文件作为输出,其中包含具有这种格式的符号列表。 (时间;主题;评论) 代码必须使用如下所示的结构函数运行循环:
struct annotation_t {
string topic;
string comment;
time_t stamp;
};
因此用户可以根据需要多次输入符号,直到他决定外出。这就是我到目前为止所做的。
#include <iostream>
#include <string>
#include <ctime>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
struct annotation_t {
string topic;
string comment;
time_t stamp;
};
int main()
{
int q = 0;
std::vector<annotation_t> obj;
do
{
annotation_t temp = {};
cout<< "input your topic: ";
cin >> temp.topic ;
cout<< "input yourfeedback: ";
cin >> temp.comment ;
cout<< "input your time stamp: ";
cin >> temp.stamp ;
cout<< "exit?";
cin >> q;
obj.push_back(temp);
} while (q != 0);
ofstream myfile("annotation.txt");
char time[1000];
for(int i = 0;i<50;i++)
{
struct annotation_t obj[i];
myfile<<obj[i].stamp <<" "; // write in file
myfile<<obj[i].topic <<" ";// write in file
myfile<<obj[i].comment; // write in file
myfile<<"\n";
}
cout<<"\nFile Created with Data with name annotation.txt \n";
myfile.close();
system("Pause");
}
退出时遇到问题。如果我输入任何值(甚至 0),我会遇到分段错误,因此我无法退出循环并将我的文件保存在 txt 中,或者如果我想输入更多内容,请重新运行它。让我知道你的想法。谢谢
【问题讨论】:
-
看@Tas 的回答。您可能希望在第二个循环中将变量名称从 i 更改为 j 以避免混淆。
-
请不要污蔑你的问题
-
Paulit 这是我试图标记为正面的错误
标签: c++ loops object while-loop ofstream