开发者

Using Strncmp with a string from a file

开发者 https://www.devze.com 2023-02-07 23:13 出处:网络
Goodnight to everyone, I\'m trying to parse an .h file so I can have a s开发者_开发知识库mall console frontend to change its values, but when I try to use strncmp with a string read from a file and a

Goodnight to everyone, I'm trying to parse an .h file so I can have a s开发者_开发知识库mall 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.


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

Also, your input loop is incorrect.


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?


if(strncmp(line.c_str(), "static float", 12) == 0){

should work


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")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号