2015-03-31 52 views
0

提供的文本文件具有未确定数量的行,每行包含3个用逗号分隔的双打。例如:如何将逗号分隔值传递给多维数组?

-0.30895,0.35076,-0.88403

-0.38774,0.36936,-0.84453

-0.44076,0.34096,-0.83035

...

我想从文件中逐行读取这些数据,然后将其拆分为逗号(,)符号并将其保存在N×3数组中,我们称之为Vertices [N] [3],其中N表示未定义的行数文件。

我迄今为止代码:

void display() { 
string line; 
ifstream myfile ("File.txt"); 
if (myfile.is_open()) 
{ 
    while (getline (myfile,line)) 
    { 
    // I think the I should do 2 for loops here to fill the array as expected 
    } 
    myfile.close(); 

} 
else cout << "Unable to open file"; 

}

的问题:我设法打开由行的文件和读取线,但我不知道如何将值传递到请求的数组。 谢谢。

编辑: 我试图修改我的代码,根据我收到的以下建议:

void display() { 
string line; 
ifstream classFile ("File.txt"); 
vector<string> classData; 
if (classFile.is_open()) 
{ 
    std::string line; 
    while(std::getline(classFile, line)) { 
     std::istringstream s(line); 
     std::string field; 
     while (getline(s, field,',')) { 
      classData.push_back(line); 
     } 
    } 

    classFile.close(); 

} 
else cout << "Unable to open file"; 

}

这是正确的?以及如何访问我创建的矢量的每个字段? (比如在一个数组中)? 我也注意到,这些是字符串类型,我怎么能将它们转换为类型浮动? 谢谢(

+1

看看http://stackoverflow.com/questions/19936483/c-reading-csv-file/19936571#19936571 – 2015-03-31 19:29:33

+0

如果有不确定数量的行,你应该使用'std :: vector',而不是一个普通的二维数组,用于存储数据。 – PaulMcKenzie 2015-03-31 19:34:47

+0

@DieterLücking我对C++相当陌生,在链接中提供的答案中,我应该在while循环中做2个?还是我误解了某个地方? – abedzantout 2015-03-31 19:43:40

回答

0

有很多方法可以解决这个问题,就我个人而言,我会实现一个链表来保存读出文件的每一行到它自己的内存缓冲区中,一旦整个文件被读出,我想知道有多少行是在文件中,并使用strtokstrtod将值转换处理列表中的每行

下面是一些伪代码让你滚。

// Read the lines from the file and store them in a list 
while (getline (myfile,line)) 
{ 
    ListObj.Add(line); 
} 

// Allocate memory for your two-dimensional array 
float **Vertices = (float **)malloc(ListObj.Count() * 3 * sizeof(float)); 

// Read each line from the list, convert its values to floats 
// and store the values in your array 
int i = j = 0; 
while (line = ListObj.Remove()) 
{ 
    sVal = strtok(line, ",\r\n"); 
    fVal = (float)strtod(sVal, &pStop); 
    Verticies[i][j++] = fVal; 

    sVal = strtok(sVal + strlen(sVal) + 1, ",\r\n"); 
    fVal = (float)strtod(sVal, &pStop); 
    Verticies[i][j++] = fVal; 

    sVal = strtok(sVal + strlen(sVal) + 1, ",\r\n"); 
    fVal = (float)strtod(sVal, &pStop); 
    Verticies[i][j] = fVal; 

    i++; 
    j = 0; 
} 
0

编辑后的代码是正确的。您可以像访问普通C++数组中的值一样访问C++中的矢量值。Like classdata[i]您可以在这里找到更多信息。 Vector reference

而关于使用将字符串转换到float.In C++,你可以直接这样做,因为你的问题的STOF即stof(-0.883)你可以找到参考这里再次string to float

好运,希望这有助于:)

相关问题