0

Forgive my C++ naivete. I need to compare two characters in the parsing of a .OBJ 3D object file. On each line iteration, the strcmp calls I make are never returning true. I have a feeling this is because I'm not up on my char* vs char knowledge. Anybody see what I'm doing wrong here?

//Variables
char* type = new char[1];

float v1;
float v2;
float v3;

//INSIDE the while loop that parses each line of the file
getline(myfile, line);
sscanf(line.c_str(),"%c %f %f %f", type, &v1, &v2, &v3);
if(strcmp(type,"f") == 0){
    faces++;
}
if(strcmp(type,"v") == 0){
vertices++;
}
George
  • 343
  • 2
  • 15

1 Answers1

3

"strcmp" compares null terminated strings, but, you have defined "type" as a single character not an array of characters terminated by x'00' as expected by strcmp.

A simple if (type == 'f') char comparison should get you the correct result.

James Anderson
  • 27,109
  • 7
  • 50
  • 78
  • Spoke too soon, it doesn't work yet. I'm crashing on sscanf(line.c_str(),"%c %f %f %f", type, &v1, &v2, &v3). I had defined type as const char* type but got a warning about type being uninitialized. So, I said const char* type = "a" and I get one of those cryptic "unhandled exception" errors on the sscanf call. (VS 2010) – George Apr 18 '12 at 05:51
  • its the "%c" which is telling scanf you expect a single character. just define type as "char" and you will be OK. – James Anderson Apr 18 '12 at 07:09
  • Tried that and changed my comparison to if (type == 'f'). Still getting a memory access error. In debug mode, when the yellow arrow is pointing to the sscanf line, type has a value of 0. When I step over the sscanf line, the memory access crash occurs. – George Apr 18 '12 at 15:24
  • Doh. It's because I needed to put &type in the sscanf call. – George Apr 18 '12 at 18:02