我想从一个包含组织名称(不含空格)和浮动整数的文本文件中收集信息。我想将此信息存储在数组结构中。
我目前遇到的问题是收集信息。以下是文本文件的示例:
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假设变量 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.
更多推荐
从文件流检测换行字节
发布评论