【问题标题】:How compare char str[MAXCHAR] with a string?如何将 char str[MAXCHAR] 与字符串进行比较?
【发布时间】:2017-05-29 16:39:28
【问题描述】:

我想比较两个序列是否相等并且我正在使用以下代码,但比较总是返回 false。

================================================ ============================

 // testecompare.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <Windows.h>

using namespace std;

string getCurrentDirectoryOnWindows()
    {
        const unsigned long maxDir = 260;
        char currentDir[maxDir];
        GetCurrentDirectory(maxDir, currentDir);
        strcat(currentDir, "\\l0gs.txt");
        return string(currentDir);
    }

    string ReadFileContent() {

        string STRING;
        string aux;
        ifstream infile;
        infile.open(getCurrentDirectoryOnWindows());
        while (!infile.eof())
        {
            getline(infile, STRING);
            return STRING;
        }
        infile.close();

        return "";

    }


int _tmain(int argc, _TCHAR* argv[])
{
     char str[MAXCHAR] = "";
    sprintf(str, "0x0%X", "1D203E5");

    cout << str << endl;
    cout << "File content: " << ReadFileContent() << endl;

    // if i have the string "0x01D203E5" in my txt file 

    if (_stricmp(str,ReadFileContent().c_str()) == 0) { 

    cout << "Contents are equals!\n"; 

}

    system("pause");
    return 0;
}

如何正确进行比较?

非常感谢。

【问题讨论】:

  • 离题:while (!infile.eof()) 是一个错误。在这里阅读更多:Why is iostream::eof inside a loop condition considered wrong?
  • 无法通过我在 minimal reproducible example 的黑客尝试进行复制。你的 MCVE 是什么样的?
  • 顺便说一句,不要给你的变量名和类型同名,比如string STRING
  • 那个sprintf 调用是错误的; %X 需要一个无符号整数类型,您传递一个 const char* 转换。而return STRING; 作为非条件语句 inside 你的循环似乎毫无意义;那里也可能没有循环。
  • 请改用sprintf(str, "0x0%s", "1D203E5");。或将str 更改为std::stringstring str = string("0x0") + "1D203E5"; ... if (str == ReadFileContent())

标签: c++ visual-c++ string-comparison


【解决方案1】:

比较不同类型实例的一个简单技巧是将它们转换为通用类型,然后进行比较。

例如:

std::string content(ReadFileContent());
std::string from_array(str)
if (from_array == content)
{
}

编辑 1:工作示例
该代码有效。
这是一个工作程序:

#include <iostream>
#include <string>

int main()
{
    static const char text[] = "Hello";
    std::string         text_as_string(text);
    std::string         expected_str("Hello");
    if (text_as_string == expected_str)
    {
        std::cout << "Strings are equal: " << text_as_string << "\n";
    }
    else
    {
        std::cout << "Strings are not equal.\n";
    }
    return 0;
}

$ g++ -o main.exe main.cpp
$ ./main.exe
Strings are equal: Hello

请记住,以上代码示例是比较整个整个字符串,而不是子字符串。如果您想在较大的字符串中搜索 键字符串,则需要不同的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多