2

Goodnight to everyone, I'm trying to parse an .h file so I can have a small console frontend to change its values, but when I try to use strncmp with a string read from a file and a string defined in code to compare with the file string I get a strange error from the compiler that I cant resolve, here is my source code:

    //Test to basic file operations
    #include <iostream>
    #include <stdio.h>
    #include <fstream>
    #include <string>
    #include <cstring>
    using namespace std;

    int main (void){

 string line;

 ifstream myfile("PIDconfig.h");
 if(myfile.is_open()){  //if file is open
  while(myfile.good()){
   getline(myfile, line);
   if(strncmp(line, "static float", 12) == 0){
    cout << line << endl;
   }
  }
  myfile.close();
 }
 else cout << "Unable to open file";

    return 0;
    }

And the error that I get:

tiago@tiago-laptop:~$ g++ file.cpp 
file.cpp: In function ‘int main()’:
file.cpp:17: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int strncmp(const char*, const char*, size_t)’

If some one could help me I would be very glad, I have already searched StackOverflow but I didnt found anyone with the same problem, almost all strncmp problems use arrays to store their strings and as far as I went, no one was having a problem using it and file I/O.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
TiagoAngelo
  • 53
  • 2
  • 4
  • Why don't you use the right tool for the job. I'm thinking of a scripting language with regex or perhaps even plain old grep? Hourses for courses. – David Heffernan Jan 31 '11 at 20:06

4 Answers4

3

std::string overloads operator==. You can simply compare two std::string object using ==.

Also, your input loop is incorrect.

Community
  • 1
  • 1
James McNellis
  • 348,265
  • 75
  • 913
  • 977
1
if(strncmp(line.c_str(), "static float", 12) == 0){

should work

Murka
  • 353
  • 4
  • 10
1

The problem is that you're reading data from the file as a C++ string, and the strncmp function works on C style strings. To fix this, you can either extract a raw C style string from the C++ string using .c_str(), or you can use the C++ string's .compare function:

line.compare(0, 12, "static float")
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
1

the problem is that strncmp() function overloaded for strncmp(const char*, const char*, int)

but you want to call it by strncmp(string, string, size_t)

you must convert string to const char* with

c_str()

for example

string str = "Hello"; char * arr = str.c_str().

you get it?

Mahdi_Nine
  • 14,205
  • 26
  • 82
  • 117