getline() in C++ - _GNU_SOURCE not needed?

2019-07-05 03:14发布

Firstly, I'm pretty new to C++. I believe that getline() isn't a standard C function, so #define _GNU_SOURCE is required to use it. I'm now using C++ and g++ tells me that _GNU_SOURCE is already defined:

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

Can anyone confirm if this is standard, or is its definition hidden somewhere in my setup? I'm not sure of the meaning of the final line quoted.

The file's includes are as follows, so presumably it's defined in one or more of these?

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

Thanks!

标签: c++ getline
3条回答
叼着烟拽天下
2楼-- · 2019-07-05 03:32

I think g++, from version 3, automagically defines _GNU_SOURCE. This is supported by your third line in the error stating that the first definition was done on the command line (with nary a -D_GNU_SOURCE in sight):

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

If you don't want it, #undef it as the first line in your compilation unit. You may need it, however, in which case use:

#ifndef _GNU_SOURCE
    #define _GNU_SOURCE
#endif

The reason you're getting the error is because you're re-defining it. It shouldn't be an error if you define it to what it already was. At least that's the case with C, it may be different with C++. Based on the GNU headers, I would say they're doing an implicit -D_GNU_SOURCE=1 which is why it thinks you're re-defining it to something else.

The following snippet should tell you its value provided you haven't changed it.

#define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n")
DBG(_GNU_SOURCE); // first line in main.
查看更多
叛逆
3楼-- · 2019-07-05 03:42

Getline is standard it is defined in two ways.
You can call it as a member function of one of streams as follows: This is the version defined in

//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');

or you can use the version defined in

//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');

for further reference http://www.cplusplus.com/reference/iostream/istream/getline.html http://www.cplusplus.com/reference/string/getline.html

查看更多
一夜七次
4楼-- · 2019-07-05 03:45

I've always had to use one of the following in C++. Never had to declare _GNU_ anything before. I usually run in *nix so I usually use gcc and g++ as well.

string s = cin.getline()

char c;
cin.getchar(&c);
查看更多
登录 后发表回答