【发布时间】: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::string:string str = string("0x0") + "1D203E5"; ... if (str == ReadFileContent())
标签: c++ visual-c++ string-comparison