将字符串与 ifstream::getline 生成的字符串进行比较
我正在开发一个项目,我需要读取 postscript 并解析文件中的数据以在我的程序中使用。我正在开发一个函数,通过确保后记具有开始和结束分隔符来测试后记是否有效。
下面是我为完成此任务而编写的代码段。我确信 postscript 文件中没有额外的空格或任何类似的内容会导致 delimitStr 和 lineStr 之间出现任何差异。我还尝试将 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.
任何帮助将不胜感激。
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. I also attempted to set delimitStr to "%%%BEGIN\0" and "%%%BEGIN", but the comparison never works.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
delimitStr
更改为delimitStr = "%%%BEGIN";
因为getline
会丢弃'\n'
和
比较像
lineStr == delimitStr
这样的字符串。不要将字符串与
c_str()
进行比较,因为它会返回const char*
。显示差异的示例:
Change
delimitStr
todelimitStr = "%%%BEGIN";
becausegetline
discards the'\n'
and
compare strings like this
lineStr == delimitStr
.DO NOT compare strings with
c_str()
as that returns aconst char*
.Example showing the differences: