简体   繁体   English

将字符串与ifstream :: getline生成的字符串进行比较

[英]Comparing strings to string produced by ifstream::getline

I am working on a project where I need to read postscript and parse data from the file to use in my program. 我正在一个项目中,我需要阅读后记并从文件中解析数据以在程序中使用。 I am working on a function to test whether the postscript is valid by making sure it has opening and closing delimiters. 我正在开发一个函数,以通过确保它具有打开和关闭定界符来测试后记是否有效。

Below is the segment of code I have written to accomplish this. 以下是我为实现此目的而编写的代码段。 I am confident that there are no additional spaces or anything of the sort in the postscript file to cause any discrepancy between delimitStr and lineStr. 我相信在postscript文件中没有其他空格或任何类似的东西会引起delimitStr和lineStr之间的任何差异。 I also attempted to set delimitStr to "%%%BEGIN\\0" and "%%%BEGIN", but the comparison never works. 我还尝试将delimitStr设置为“ %%% BEGIN \\ 0”和“ %%% BEGIN”,但是比较从未成功。

string lineStr;
bool beginFlag = false; //Switches to true when begin statement in postscript is found
string delimitStr = "%%%BEGIN"; //Starts as opening  delimiter. Switches to closing when opening is found.
while(psfile) {
    getline(psfile, lineStr);
    if(!beginFlag && lineStr == delimitStr) {
        beginFlag = true;
        delimitStr = "%%%END";
        cerr << "Begin found." << endl;
    }
    else if(beginFlag && lineStr == delimitStr)
        return true; //Only return true if file has beginning and ending delimiters.

Any help would be greatly appreciated. 任何帮助将不胜感激。

Change delimitStr to delimitStr = "%%%BEGIN"; 改变delimitStrdelimitStr = "%%%BEGIN"; because getline discards the '\\n' and compare strings like this lineStr == delimitStr . 因为getline会丢弃'\\n'并比较类似于lineStr == delimitStr字符串。 DO NOT compare strings with c_str() as that returns a const char* . 不要将字符串与c_str()比较,因为这会返回const char*

Example showing the differences: 显示差异的示例:

std::string s1("%%%BEGIN");
std::string s2("%%%BEGIN\n");
std::string s3("%%%BEGIN\0"); // Same as s1 because std::string stops at '\0'

std::cout << std::boolalpha << (s1 == s2) << '\n';      // Outputs: false
std::cout << (s1 == s3) << '\n';      // Outputs: true 
std::cout << (s2 == s3) << std::endl; // Outputs: false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM