检测从FILESTREAM换行符字节
-
22-07-2019 - |
题
我想从其中包含的组织名称(无空格)和浮点整数一个文本收集信息。我想存储在一个阵列结构这一信息。
我有迄今为止的问题是收集的信息。下面是文本文件的一个示例:
CBA 12.3 4.5 7.5 2.9 4.1
3.9 TLS 8.6 1 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 << "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();
}
我想要在我的GetData功能实现这一目标是:第一存储组织名称到结构,然后读取每个浮点到数据阵列中,直至程序检测到一个换行符字节。然而,到目前为止,我对换行字节的校验不能正常工作。
假设变量的 C 和 MAX 的已被定义。
我应该如何去吗正确?
解决方案
char byte = ins.peek();
或者
if(ins.peek() == '\n') break;
(编辑):你还需要检查),包括您PEEK(后一个EOF,因为某些文件可能不会有结束的换行
我想指出的是,你可能要考虑使用vector<callCentre>
,而不是一个静态数组。如果你输入的文件长度超过阵列的容量,你会走在整个堆栈。
其他提示
>>运算符把空格作为分隔符,并包括换行符,所以它只是吃那些和你永远看不到它们。
您需要阅读线,然后剁成排队。两轮牛车的以下位示出的基本思想:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string line;
while( getline( cin, line ) ) {
istringstream is( line );
string cs;
is >> cs;
double vals[10];
int i = 0;
while( is >> vals[i] ) {
i++;
}
cout << "CS: " << cs;
for ( int j = 0; j < i; j++ ) {
cout << " " << vals[j];
}
cout << endl;
}
}
我将读取文件,一个接一个的线和单独分析每个线对的值:
std::string line;
while (std::getline(ins, line)) {
std::istringstream sline(line);
sline >> aCentre[c].name;
int i = 0;
while (sline >> aCentre[c].data[i])
i++;
c++;
}
不隶属于 StackOverflow