2015-04-04 56 views
0

我有一个看起来像这样的文件:读取多个变量类型从文件

5,4,A 
6,3,A 
8,7,B 
7,6,B 
5,2,A 
9,7,B 

我试图创建一个类函数读取一行和内容插入到X,分别ÿfeatClass。变量类型是int x,y和char featClass。从这一点开始,我可以创建一个名为sample1的类的对象,该类将包含文件中相应行中的x,y和featClass。

为了澄清,每行代表一个样本。我将为每个样本行创建我的类的对象,并将对象命名为sample1,sample2等...

我编写了代码来读取main中的文件,以确保它在插入代码到我的班级功能。但是,当我运行程序并将第一行读入x,y和featClass时,每个变量的结果值分别为1,0,P,这与第一行5,4,A不匹配。

这是到目前为止我的代码:

#include <iostream> 
#include <cmath> 
#include <fstream> 
#include <cstdlib> 
using namespace std; 

int main() 
{ 
    //init variables 
    int x,y; 
    char featClass; 

    //get x,y, and output params from input file 
    char filename[50]; 
    ifstream sampleFile("sampleFile.txt"); 
    //cin.getline(filename,50); 
    sampleFile.open(filename); 

    if(!sampleFile.is_open())//check if file is not open 
    { 
    exit(EXIT_FAILURE);//terminates program if file is not opened correctly 
    }; 

    while(sampleFile.peek() == ',') 
    { 
    sampleFile.ignore(1);` 
    sampleFile >> x >> y >> featClass; 
    }; 

    cout << x << " " << y << " " << featClass << endl; 

    return 0; 
} 

我不知道为什么我的代码输出1,0,P为X,Y和featclass。

回答

0

我注意到一个'sampleFile.ignore(1); 我要做的是做一个迭代遍历每个字符的语句,寻找匹配“1”,如果找到了,就将其删除。

+0

我不明白的是为什么它会返回这些值?在我阅读的文本文件的任何地方都没有找到3个值。 – 2015-04-05 00:29:17

0

而不是cin.peek(),你应该使用getline()来读取整行。

while(getline(sampleFile, line)) 
    { 
    //do stuff here 
    }; 

然后,解析线和使用stringstream

所以你的代码(阅读文件,并解析它)的值存储到X,Y和featClass将类似于此:

char ch; <-- include this for comma 
    while(getline(sampleFile, line)) 
    { 
     //do stuff here 
     stringstream sstream(line); 
     //this is for your particular problem as your file format is --> int, int, char 
     sstream >> x >> ch >> y >> ch >> featClass; 
     cout << x << " " << y << " " << featClass << endl; 
    }; 

查看此链接阅读并了解更多关于stringstream

http://www.eecis.udel.edu/~breech/progteam/stringstream.html