C ++:用fgetc读取csv文件,用分号“;”分隔单词

时间:2013-11-04 20:36:46

标签: c++ arrays csv struct

我必须在包含5个字段(int,char [],char [],char [],float)的csv文件中读取,如下所示:

2345678;Meier;Hans;12.10.1985;2.4;      
1234567;Müller;Fritz;17.05.1990;1.9;

我必须将字段放在一个结构中,然后在一行完成之后将结构放入结构类型的数组中......

对于学习效果,我们只允许使用LOW-LEVEL编码,只使用fgetc,strcpy和无字符串等函数,只有char [] ... 现在我让我的算法逐个字符地读取文本文件,但是我在将它们正确分开时会出现问题,将它们再次组合在一起并正确地将它们分配给struct字段。这是我的代码:

  #include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char **argv)
{
    struct Stud{
        long matrnr;
        char vorname[30];
        char name[30];
        char datum[30];
        float note;
    };

    const int MAX = 30;
    Stud stud;  
    Stud mystud[30]; // <<-- Array of "Stud" type
    //memset((void*)mystud,0,sizeof(mystud) * sizeof(Stud));
    int wordCounter(0);
    int i(0); //thats the charCounter or index
    int studentCounter(0);
    char wort[MAX];
    //int matrnr;
    //char vorname[MAX];
    //char name[MAX];
    //char datum[MAX];
    //float note;


  FILE * pFile;
  int cnr(0); 


  pFile=fopen("studentendaten.txt","r");  
  if (pFile==nullptr) 
  {
      perror ("Fehler beim öffnen der Datei");
  }

  else
  {       
    while (cnr != EOF) 
    {       
        (cnr=fgetc(pFile)) ;


        if ((char)cnr == '\n') {
            mystud[studentCounter] = stud;
            studentCounter++;                       
            continue;           
        }

        if ((char)cnr == ';') { 

            wort[i] = '\0'; 

            switch (wordCounter % 5) {

                case 0:             
                stud.matrnr = atol(wort);
                break;

                case 1:
                strcpy(stud.name, wort);
                break;

                case 2:
                strcpy(stud.vorname, wort);
                break;

                case 3:
                strcpy(stud.datum,wort);
                break;

                case 4:
                stud.note = atof(wort); 
                break;
            }       

            wordCounter++;          
            i = 0;
            continue;
        }

        if (wordCounter %  5 == 0 && (char)cnr != ';') {        
        wort[i] = (char)cnr;
        i++;
        //stud.matrnr = atol(wort);
        }           

        if (wordCounter % 5 == 1) {
            wort[i] =  (char)cnr;
            i++;
        //strcpy(stud.name, wort);
        }

        if (wordCounter % 5 == 2) {
            wort[i] = (char)cnr;
            i++;
            //strcpy(stud.vorname, wort);
        }

        if (wordCounter % 5 == 3) {
            wort[i] = (char)cnr;
            i++;
            //strcpy(stud.datum,wort);
        }

        if (wordCounter % 5 == 4) {
            wort[i] = (char)cnr;
            i++;
            //stud.note = atof(wort);                       
        }

    }   


    fclose (pFile);
}
for (int i(0) ; i <= studentCounter; i++) {
cout <<mystud[i].matrnr << "    " << mystud[i].name << "    " << mystud[i].vorname <<"    " 
<< mystud[i].datum <<"    " << mystud[i].note << endl;
  //printf("%5ld        %5s      %5s     %5s     %5f     \n",mystud[i].matrnr,mystud[i].name,mystud[i].vorname,mystud[i].datum,mystud[i].note);

}

    return 0;
}

我不确定它是否与错误的增量变量有关,或者我没有在我的wort []数组的末尾加上'\ 0',因此无法识别结束我的阵列?如果是这样的话,我怎么做呢却不知道结局到底在哪里......? (我不知道单词的长度..)

编辑:我再次更新了我的代码,唯一让我感到惊讶的是,最后一行没有正确分辨,它显示了一些垃圾,我在代码中看不到错误......

2345678;Meier;Hans;12.10.1985;2.4;      
1234567;Müller;Fritz;17.05.1990;1.9;
8392019;Thomas;Kretschmer;28.3.1920;2.5;
3471144;Mensch;Arbeit;29.2.2013;4.5;
2039482;Test;Test;30.20.2031;2.0;
7584932;Bau;Maschine;02.02.2010;2.3;
2345678;Meier;Hans;12.10.1985;2.4;      
1234567;Müller;Fritz;17.05.1990;1.9;
8392019;Thomas;Kretschmer;28.3.1920;2.5;
3471144;Mensch;Arbeit;29.2.2013;4.5;
2039482;Test;Test;30.20.2031;2.0;
7584932;Bau;Maschine;02.02.2010;2.3;
2345678;Meier;Hans;12.10.1985;2.4;      
1234567;Müller;Fritz;17.05.1990;1.9;
8392019;Thomas;Kretschmer;28.3.1920;2.5;
3471144;Mensch;Arbeit;29.2.2013;4.5;
2039482;Test;Test;30.20.2031;2.0;
7584932;Bau;Maschine;02.02.2010;2.3;
2345678;Meier;Hans;12.10.1985;2.4;      
1234567;Müller;Fritz;17.05.1990;1.9;
8392019;Thomas;Kretschmer;28.3.1920;2.5;
3471144;Mensch;Arbeit;29.2.2013;4.5;
2039482;Test;Test;30.20.2031;2.0;
7584932;Bau;Maschine;02.02.2010;2.3;

3 个答案:

答案 0 :(得分:1)

建议:使用case结构进行解析,并使自己成为“copyToSemicolon”函数:然后你可以编写像

这样的东西
sIndexCount = 0;
char temp[50];
while((cnr=fgetc(pFile)) != EOF) {
  offset = 0;
  for(var = 0; var < 5; var++ {
    switch(var) {
    case 0:
      offset = copyToSemicolon(temp, cnr, offset) + 1;
      stud.matrnr = atoi(temp);
      break;
    case 1:
      offset = copyToSemicolon(mystud[sIndexCount].vorname, cnr, offset) + 1;
      break;
    ... etc
    }
  }
  sIndexCount++;
  if(sIndexCount == 50) break;  // in case the input file is longer than our structure
}

你需要一个函数copyToSemicolon,它将两个char*指针作为输入,并从第二个字符串(从offset开始)复制字符,直到它到达分号或者行尾 - 并返回它到达的偏移量(读取最后一个字符)。

int copyToSemicolon(char* dest, char* source, int offset) {
  while(source[offset] != ';' && source[offset] != '\n') {
    *dest = source[offset++];
    dest++;
  }
  return offset;
} 

编辑 strtok方法:

sIndexCount = 0;
char temp[50];
while((cnr=fgetc(pFile)) != EOF) {
  offset = 0;
  temp = strtok(cnr, ';');
  for(var = 0; var < 5; var++ {
    switch(var) {
    case 0:
      stud.matrnr = atoi(temp);
      break;
    case 1:
      strcpy(mystud[sIndexCount].vorname, strtok(NULL, ';'));
      break;
    ... etc
    case 4:
      mystud[sIndexCount].note = atof(strtok(NULL, '\n'));
    }
  }
  sIndexCount++;
  if(sIndexCount == 50) break;  // in case the input file is longer than our structure
}

答案 1 :(得分:0)

我看到的一个问题是您的代码一次复制或解析一个字符,这样当您阅读2345678;Meier;Hans;12.10.1985;2.4;时,您首先将stud.matrnr设置为2,然后设置为23,然后是234然后是2345,然后是23456,然后是234567,然后是2345678.同样地,对于stud.name,你首先将它设置为M,然后是Me,然后是Mei,等等。我建议你用不同的东西来思考办法。我会给你一些伪代码:

while (!eof) {
    get character from file
    if (character isn't ';' and isn't '\n') {
        copy character into buffer (increment buffer index)
    } else if (character is ';') {
        it's the end of a word.  Put it in its place - turn it to an int, copy it, whatever
        reset the buffer
    } else if (character is '\n') {
        it's the end of the last word, and the end of the line.  Handle the last word
        reset the buffer
        copy the structure
    }
}

这会让你的生活变得更轻松。您几乎没有更改数据,如果需要调试,您可以专注于每个部分。

通常,在编程中,第一步是确保您可以用母语说出您想要做的事情,然后将其转换为代码更容易。你很接近你的实现,你可以使它工作。当你看到';'时,请确保你可以解释应该发生什么。或'\ n'。

答案 2 :(得分:0)

由于您已将其标记为C ++,因此您应该考虑使用std::getline来读取文件中的行,使用std::getline(file, text_before_semicolon, ';')来解析字段。

您还可以使用std::istringstream将文本行中的文字表示转换为内部数字格式。