3

まず、私は 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

これが標準なのか、それとも設定のどこかにその定義が隠されているのか、誰でも確認できますか? 引用された最後の行の意味がわかりません。

ファイルのインクルードは次のとおりです。おそらく、これらの 1 つまたは複数で定義されていますか?

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

ありがとう!

4

3 に答える 3

5

バージョン 3 からの g++ は、自動的に を定義すると思います_GNU_SOURCE。これは、最初の定義がコマンドラインで行われたことを示すエラーの 3 行目でサポートされています (ほとんど-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していると考える理由です。

次のスニペットは、変更していない限り、その値を示しているはずです。

#define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n")
DBG(_GNU_SOURCE); // first line in main.
于 2009-02-18T01:16:35.673 に答える
0

Getlineは標準であり、2つの方法で定義されます。
次のように、いずれかのストリームのメンバー関数として呼び出すことができます。これは、で定義されているバージョンです。

//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

于 2009-02-18T03:01:59.853 に答える
0

私は常に C++ で次のいずれかを使用する必要がありました。以前は _GNU_ を宣言する必要はありませんでした。私は通常 *nix で実行するので、通常は gcc と g++ も使用します。

string s = cin.getline()

char c;
cin.getchar(&c);
于 2009-02-18T01:12:23.547 に答える