C++ 中对象的循环问题

Loop Issues with objects in C++

本文关键字:循环 问题 对象 C++      更新时间:2023-10-16

我必须创建一个简单的代码,该代码应该创建一个.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 中,或者如果我想输入更多,请重新运行它。让我知道你的想法,谢谢

int i=0;
struct annotation_t obj[i];

您正在创建大小0 annotation_t对象的数组

cin >> obj[i].topic ;

然后尝试访问第一个元素。

请考虑改用std::vector,这将允许您动态更改容器的大小,以允许用户输入任意数量的容器:

// Empty container
std::vector<annotation_t> obj;
do
{
    // Create temporary
    annotation_t temp = {};
    // Accept input:
    cin >> temp.topic;
    ...
    // Add to container:
    obj.push_back(temp);
}

在你的下面for循环中,你正在做与上面相同的事情

for(int i = 0;i<50;i++) 
{
struct annotation_t obj[i];

另外,您正在创建一个新容器。您可能打算使用上面的容器,这会将您的循环更改为:

// Store the contents of the now populated obj from above
for (auto& a : obj)
{
    myfile << a.stamp << " ";
    myfile << a.topic << " ";
    myfile << a.comment << std::endl;
}

声明"obj"对象时遇到问题。这是错误的:

struct annotation_t obj[i];

试试这个:

#include <iostream>
#include <string>
#include <ctime>
#include <fstream>
#include <cstdlib>

using namespace std;
struct annotation_t {
string topic;
string comment;
time_t stamp;
};
int main()
{
int q = 0;
struct annotation_t obj[1000]; //msf
int i=0; //msf
do
{
cout<< "input your topic";
cin >> obj[i].topic ;
cout<< "input yourfeedback";
cin >> obj[i].comment ;
cout<< "input your time stamp";
cin >> obj[i].stamp ;
cout<< "exit?";
cin >> q ;
i++; //msf
} while (q != 0);  

ofstream myfile("annotation.txt");
int count=i; //msf
for(i = 0;i<count;i++)  //msf
{
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");
}

我在用"//msf"注释的许多位置更改了您的代码。我手头没有C++编译器,那么我希望它能被编译而没有错误。