从文件流检测换行字节

编程入门 行业动态 更新时间:2024-10-25 13:17:06
本文介绍了从文件流检测换行字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想从一个包含组织名称(不含空格)和浮动整数的文本文件中收集信息。我想将此信息存储在数组结构中。

我目前遇到的问题是收集信息。以下是文本文件的示例:

CBA 12.3 4.5 7.5 2.9 4.1

TLS 3.9 1 8.6 12.8 4.9

每个组织最多可以有128个不同的号码,文本文件中最多可以有200个组织。

这是我的结构到目前为止:

struct callCentre { char name [256]; float data [20]; };

我的主要:

int main() { callCentre aCentre [10]; getdata(aCentre); calcdata(aCentre); printdata(aCentre); return 0; }

和getdata函数:

void getdata(callCentre aCentre []) { ifstream ins; char dataset [20]; cout<< 输入数据文件的名称:; cin>>数据集; ins.open(dataset); if(ins.good()) { while(ins.good()) { ins> aCentre [c] .name; for(int i = 0; i 我想在getdata函数中实现的是:组织名称首先进入结构,然后将每个float读入数据数组,直到程序检测到换行符字节。但是,到目前为止,我对换行字节的检查是无效的。

假设变量 c

解决方案

pre> char byte = ins.peek();

if(ins.peek()=='\\\')break;

(编辑):你还需要检查你的peek一些文件可能没有结束换行符。

我想指出,您可能需要考虑使用向量< callCentre& / code>而不是静态数组。如果你的输入文件长度超过了数组的容量,你将遍历堆栈。

I'm trying to collect information from a textfile which contains names of organisations (without spaces) and floating integers. I want to store this information in an array structure.

The problem I'm having so far is collecting the information. Here is a sample of the textfile:

CBA 12.3 4.5 7.5 2.9 4.1

TLS 3.9 1 8.6 12.8 4.9

I can have up to 128 different numbers for each organisation, and up to 200 organisations in the textfile.

This is what my structure looks like so far:

struct callCentre { char name[256]; float data[20]; };

My main:

int main() { callCentre aCentre[10]; getdata(aCentre); calcdata(aCentre); printdata(aCentre); return 0; }

And the getdata function:

void getdata(callCentre aCentre[]) { ifstream ins; char dataset[20]; cout << "Enter the name of the data file: "; cin >> dataset; ins.open(dataset); if(ins.good()) { while(ins.good()) { ins >> aCentre[c].name; for(int i = 0; i < MAX; i++) { ins >> aCentre[c].data[i]; if(ins == '\n') break; } c++; } } else { cout << "Data files couldnt be found." << endl; } ins.close(); }

What I'm trying to achieve in my getdata function is this: store the organisation name first into the structure, then read each float into the data array until the program detects a newline byte. However, so far my check for the newline byte isn't working.

Assume that variables c and MAX are already defined.

How should I go about this properly?

解决方案

char byte = ins.peek();

Or

if(ins.peek() == '\n') break;

(Edit): You'll want to also check for an eof after your peek(), because some files may not have a ending newline.

I'd like to point out that you might want to consider using a vector<callCentre> instead of a static array. If your input file length exceeds the capacity of the array, you'll walk all over the stack.

更多推荐

从文件流检测换行字节

本文发布于:2023-11-12 07:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   换行   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!