以正确的模式打印数据
Printing Data In The Right Pattern
我编写了一个函数,该函数遍历文本文件并读取所有数据并将其打印出来,但是显示数据的格式是错误的,它只是逐行打印出数据,如下所示:
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;
}
}
相关文章:
- 从C++调用 Python 脚本以持续流式传输数据
- 在打印方法中,难以在二进制树中打印数据
- 面对迭代矢量<矢量<string>>和打印数据的问题
- 使用访问器以两种格式打印数据
- 如何在我从文件中读取的结构中打印数据
- 悬挂式C 打印形状来自字符串阵列
- 从 txt 文件中查找和打印数据
- 如何在 c++ 中的字符串中显式打印“”
- 使用函数和数组从文件中读取和打印数据
- 通过C++从标准输出中的一些打印数据中提取特定值
- 以十六进制打印数据结构值
- 以正确的模式打印数据
- 使用Boost::ASIO连续流式传输数据,无需关闭套接字
- C++:打印数据,printf
- for_each打印数据不正确
- 在链表节点中递归打印数据,但使用多个前向链接C++(包括Pic)
- C++运算符语法,用于处理 a = b + c,而无需在 "a.data_ptr" 中显式复制数据
- 返回不同的数据类型,而无需显式指定数据类型
- 在矢量中打印数据
- 我可以隐式刷新数据吗?