【问题标题】:Using Strncmp with a string from a file将 Strncmp 与文件中的字符串一起使用
【发布时间】:2011-06-18 19:54:52
【问题描述】:

大家晚安,我正在尝试解析一个 .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 时遇到问题。

【问题讨论】:

  • 为什么不使用正确的工具来完成这项工作。我正在考虑使用正则表达式甚至是普通的旧 grep 的脚本语言?课程时间。

标签: c++ string file-io iostream


【解决方案1】:

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

另外,your input loop is incorrect.

【讨论】:

    【解决方案2】:

    问题在于 strncmp() 函数为 strncmp(const char*, const char*, int) 重载

    但你想通过 strncmp(string, string, size_t) 调用它

    您必须使用

    将字符串转换为 const char*

    c_str()

    例如

    字符串 str = "你好"; char * arr = str.c_str().

    你明白了吗?

    【讨论】:

      【解决方案3】:
      if(strncmp(line.c_str(), "static float", 12) == 0){
      

      应该工作

      【讨论】:

        【解决方案4】:

        问题是您从文件中读取数据作为 C++ 字符串,而 strncmp 函数适用于 C 样式字符串。要解决此问题,您可以使用 .c_str() 从 C++ 字符串中提取原始 C 样式字符串,也可以使用 C++ 字符串的 .compare 函数:

        line.compare(0, 12, "static float")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-03
          • 1970-01-01
          • 2016-04-24
          • 1970-01-01
          • 2014-11-27
          • 2017-04-30
          相关资源
          最近更新 更多