我正在编写一个应该读取 OFF 文件的类,但我遇到了以下问题:
如果我在 Code::Blocks 环境中编译它,一切正常。 如果要加载的文件的第一行与“OFF”不同,它将跳转到第二个 if 语句并退出程序...
但是,如果我在 cygwin 中使用 g++ 进行编译,则无论文件中实际写入了什么,程序都会跳转到第二个 if 语句。 有什么建议吗?
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
polyeder offManager::readOFF(std::string filename)
{
//Open File
std::ifstream file(filename.c_str());
// If file couldn't be opened
if( !file.is_open() )
{
std::cerr << "ERROR: Konnte Datei \""
<< filename << "\" nicht oeffnen!"
<< std::endl;
exit (2);
}
// Test if the file really is an OFF File
std::string line;
std::string off ("OFF");
getline( file, line );
if ( line.compare(off) != 0 )
{
std::cerr << "ERROR: Datei \""
<< filename << "\" ist nicht im OFF Format!"
<< std::endl;
file.close();
exit (2);
}
...
}
如果我在 cygwin 中键入 g++ -v,我会得到以下信息: 布拉布拉布拉 线程模型:posix gcc-版本 4.5.3 (GCC)
Code::Blocks 使用这个版本: 线程模型:win32 gcc 版本 4.4.1 (TDM-2 mingw32)
最佳答案
您打开的文件可能是 DOS 文本格式,因此它的行以 \r\n
结尾,而不仅仅是 \n
。
Cygwin 常见问题解答中有一个关于 this issue 的条目.我将您的代码复制到一个简单的 main
驱动程序中,并以两种方式编译它。一、常规方式:
$ g++ s.cc
$ ./a.exe test
ERROR: Datei "test" ist nicht im OFF Format!
然后,使用建议的修复(以文本翻译模式打开,以二进制模式写入):
$ g++ s.cc /usr/lib/automode.o
$ ./a.exe test
关于如果我不使用 Code::Blocks 但使用 cygwin 进行编译,c++ compare std::string 将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11485568/