gpt4 book ai didi

c++ - 将 Strncmp 与文件中的字符串一起使用

转载 作者:搜寻专家 更新时间:2023-10-31 00:21:14 25 4
gpt4 key购买 nike

大家晚安,我正在尝试解析一个 .h 文件,这样我就可以有一个小的控制台前端来更改它的值,但是当我尝试将 strncmp 与从文件中读取的字符串和代码中定义的字符串一起使用时为了与文件字符串进行比较,我从编译器中得到了一个我无法解决的奇怪错误,这是我的源代码:

    //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;
}

我得到的错误:

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)’

如果有人能帮助我我会很高兴,我已经搜索过 StackOverflow 但我没有发现任何人有同样的问题,几乎所有的 strncmp 问题都使用数组来存储他们的字符串,据我所知,没有人是在使用它和文件 I/O 时遇到问题。

最佳答案

std::string 重载 operator==。您可以使用 == 简单地比较两个 std::string 对象。

此外,your input loop is incorrect.

关于c++ - 将 Strncmp 与文件中的字符串一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4855389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com