如果我不使用 Code::Blocks 但使用 cygwin 进行编译,c++ compare std::string 将不起作用

标签 c++ g++ cygwin compare stdstring

我正在编写一个应该读取 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/

相关文章:

Node.js:如何安装 NPM

c++ - 使用 socket recv 函数读取 stdin 上的流

c++ - TS Concepts 类型名约束

c++ - C++ 中以 5 结尾的 float 的不同舍入结果

ruby - 无法在 Cygwin 中使用 RVM 安装 ruby​​ - curl SSL 证书问题

python - Cygwin 安装程序不安装 gdb.exe

c++ - 为什么推导出这里的类型是uint32_t呢?

c++ - g++ 4.4 中大括号初始化的替代方法

gcc - g++ 'nullptr' 未在此范围内声明

C++ Debian SDL 段错误