【问题标题】:getline() in C++ - _GNU_SOURCE not needed?C++ 中的 getline() - _GNU_SOURCE 不需要?
【发布时间】:2010-10-08 05:59:12
【问题描述】:

首先,我对 C++ 还是很陌生。我相信getline() 不是标准的C 函数,所以需要#define _GNU_SOURCE 才能使用它。我现在使用 C++,g++ 告诉我 _GNU_SOURCE 已经定义:

$ g++ -Wall -Werror parser.cpp
parser.cpp:1:1: error: "_GNU_SOURCE" redefined
<command-line>: error: this is the location of the previous definition

谁能确认这是标准的,还是它的定义隐藏在我的设置中的某个地方?我不确定最后一行引用的含义。

文件的includes如下,大概是在其中一个或多个中定义的吧?

#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <list>
#include <sstream>

谢谢!

【问题讨论】:

    标签: c++ getline


    【解决方案1】:

    我认为从版本 3 开始的 g++ 会自动定义 _GNU_SOURCE。错误中的第三行支持这一点,指出第一个定义是在命令行上完成的(看不到 -D_GNU_SOURCE):

    <command-line>: error: this is the location of the previous definition
    

    如果你不想要它,#undef 它作为你编译单元的第一行。但是,您可能需要它,在这种情况下使用:

    #ifndef _GNU_SOURCE
        #define _GNU_SOURCE
    #endif
    

    您收到错误的原因是您正在重新定义它。如果您将它定义为它已经是什么,它不应该是一个错误。至少 C 是这样,C++ 可能会有所不同。基于 GNU 标头,我会说他们正在做一个隐含的-D_GNU_SOURCE=1,这就是为什么它认为你正在重新定义它到别的东西。

    如果你没有改变它,下面的 sn-p 应该告诉你它的值。

    #define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n")
    DBG(_GNU_SOURCE); // first line in main.
    

    【讨论】:

    • 感谢您的回复,为我解决了问题。为了兼容性,我将按照建议使用预处理器。
    • 最后的两行 sn-p 不太对:您需要额外的宏扩展级别。三行sn-p(1) #define STRINGIZE(x) #x (2) #define DBG(x) printf (#x"=["STRINGIZE(x)"]\n") (3) DBG(_GNU_SOURCE);给我:_GNU_SOURCE=[1]
    • 而且,更一般地说,DBG(x) 或许应该被#define 定义为printf("%s\n", ...etc...),以处理#x 包含% 的远程可能性。
    【解决方案2】:

    我一直不得不在 C++ 中使用以下其中一种。以前从来不需要声明 _GNU_ 任何东西。我通常在 *nix 中运行,所以我通常也使用 gcc 和 g++。

    string s = cin.getline()
    
    char c;
    cin.getchar(&c);
    

    【讨论】:

    【解决方案3】:

    Getline 是标准的,它以两种方式定义。
    您可以将其称为流之一的成员函数,如下所示: 这是在

    中定义的版本
    //the first parameter is the cstring to accept the data
    //the second parameter is the maximum number of characters to read
    //(including the terminating null character)
    //the final parameter is an optional delimeter character that is by default '\n'
    char buffer[100];
    std::cin.getline(buffer, 100, '\n');
    

    或者你可以使用在

    中定义的版本
    //the first parameter is the stream to retrieve the data from
    //the second parameter is the string to accept the data
    //the third parameter is the delimeter character that is by default set to '\n'
    std::string buffer;
    std::getline(std::cin, buffer,'\n');
    

    供进一步参考 http://www.cplusplus.com/reference/iostream/istream/getline.html http://www.cplusplus.com/reference/string/getline.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-01
      • 2014-08-31
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多