以正确的模式打印数据

Printing Data In The Right Pattern

本文关键字:式打印 数据 模式      更新时间:2023-10-16

我编写了一个函数,该函数遍历文本文件并读取所有数据并将其打印出来,但是显示数据的格式是错误的,它只是逐行打印出数据,如下所示:

 james
 c 18 6 endah regal
 male
 0104252455
 rodgo.james
 kilkil

我正在寻找显示数据的内容是这样的(目前没有发生):

 Name : james
 Address : c 18 6 
 Gender : Male 
 Contact : 0104252455
 Username : rodgo.james
 Password : kilkil

这是函数:

 int molgha() {
    ifstream in("owner.txt");
    if (!in) {
        cout << "Cannot open input file.n";
        return 1;
    }
    char str[255];
    while (in) {
        in.getline(str, 255);  // delim defaults to 'n'
        if (in) cout << str << endl;
    }
    system("pause");
    in.close();
  }

请记住,此文本文件包含注册到系统的所有者的记录,因此我们可能需要打印出 3 组具有相同模式的所有者数据而没有任何错误,因此连续显示数据的最佳方法是什么?

您没有在代码中打印出所需的名称,地址等标签。您有两种选择——

1)在实际文件本身的数据之前写出标签,并保留打印代码2)有一个结构或一个类,带有成员名称,地址等和一个打印内容的函数

struct FileEntry{
  string name;
  string address;
  .
  .
  .
  void printContents(){
    cout << "Name: " << name << endl;
    cout << "Address: " << address << endl;
    // etc etc
  }
}

如果您希望每个文件具有不同数量的记录,只需在文件顶部放置一个数字,即如果文件包含 100 条记录,请将 100 作为要读入的第一条数据并在处理中使用它

int numRecords;
ifstream in;
if(in.open("owners,txt")){
  numRecords << in;
 for(int record = 0; record < numRecords; records++){
   //read the info and output it here   
 }

你想要存储你的输出名称名称,如下所示:

std::vector<std::string> names { "Name", "Address", "Gender", "Contact", "Username", "Password" };

带一个互动者去它:

auto it = names.begin();

并在while循环中打印:

if (in) cout << *it++ << " : " << str << endl;

只需添加一个标签数组,并根据您从文件中获取的行打印它们。

const string labels[6] = {
    "Name", "Address", "Gender", "Contact", "Username", "Password"
};
int i = 0;
while (in) {
    in.getline(str, 255);  // delim defaults to 'n'
    if (in) {
        if (i == 6) i = 0;
        cout << labels[i++] << " : " << str << endl;
    }
}

所以重申你的问题:

如何将字段名称:、地址:等添加到输出中。

我建议采用以下方法:

在静态数组中声明字段名称:

const char* fieldNamesArray[6] = { "Name","Address","Gendre", "Contact","Username","Password"};

在您的读/写函数中,使用每个非空行并假设所有条目都有 6 个字段并且所有时间都以相同的顺序:

int curField=0;
while(in)
{
    in.getLine(str,255);
    if (strlen(str)>0)
    {
        cout<< fieldsNamesArray[curField] << " : " << str;
        curField++;
    }
    if (curField>=6)
    {
       curField=0;
    }
}