48

ユーザー入力の行全体を取得して文字列名に入れるには、次のプログラムが必要です。

cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;

getline(cin, names);

ただし、cin >> numberコマンドの前にあるgetline()コマンド(これが問題だと思います)では、名前を入力できません。なんで?

コマンドについて何か聞いたのですcin.clear()が、これがどのように機能するのか、なぜこれが必要なのかわかりません。

4

13 に答える 13

26
cout << "Enter the number: ";
int number;
cin >> number;

cin.ignore(256, '\n'); // remaining input characters up to the next newline character
                       // are ignored

cout << "Enter names: ";
string names;
getline(cin, names);
于 2012-07-08T19:11:47.327 に答える
20

それを行う別の方法は、

cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' ); 

入力バッファを完全にフラッシュした後cin>>number;(改行が見つかるまで余分な文字をすべて拒否します)。メソッド#include <limits>を取得する必要があります。max()

于 2011-04-21T05:53:23.060 に答える
11
cout << "Enter the number: ";
int number;
if (cin >> number)
{
    // throw away the rest of the line 
    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }
    cout << "Enter names: ";
    string name;
    // keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
    while (getline(cin, name))
        ...use name...
}
else
{
    std::cerr << "ERROR reading number\n";
    exit(EXIT_FAILURE);
}

上記のコードでは、このビット...

    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }

...数値に空白のみが含まれた後、入力行の残りの部分をチェックします。

無視してみませんか?

これはかなり冗長なので、ignore後のストリームで使用すること>> xは、コンテンツを次の改行まで破棄するためによく推奨される代替方法ですが、空白以外のコンテンツを破棄して、ファイル内の破損したデータを見落とすリスクがあります。ファイルのコンテンツが信頼できるかどうか、破損したデータの処理を回避することがどれほど重要かなどに応じて、気にする場合と気にしない場合があります。

では、いつclearを使用して無視しますか?

したがって、std::cin.clear()(およびstd::cin.ignore())はこれには必要ありませんが、エラー状態を削除するのに役立ちます。たとえば、ユーザーに有効な番号を入力する機会を多く与えたい場合です。

int x;
while (std::cout << "Enter a number: " &&
       !(std::cin >> x))
{
    if (std::cin.eof())
    {
        std::cerr << "ERROR unexpected EOF\n";
        exit(EXIT_FAILURE);
    }

    std::cin.clear();  // clear bad/fail/eof flags

    // have to ignore non-numeric character that caused cin >> x to
    // fail or there's no chance of it working next time; for "cin" it's
    // common to remove the entire suspect line and re-prompt the user for
    // input.
    std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}

スキップなどでもっと簡単にできませんか?

ignore元の要件に代わるもう1つの単純ですが、中途半端な代替手段は、std::skipws行を読み取る前に任意の量の空白をスキップするために使用することです...

if (std::cin >> number >> std::skipws)
{
    while (getline(std::cin, name))
        ...

...しかし、「1E6」のような入力を取得した場合(たとえば、1,000,000を入力しようとしている科学者が、C ++は浮動小数点数の表記のみをサポートしている場合)、それを受け入れない場合は、にnumber設定され1、次のようにE6読み取られます。の最初の値name。これとは別に、有効な番号の後に1つ以上の空白行がある場合、それらの行は黙って無視されます。

于 2011-04-21T05:50:34.780 に答える
10

試す:

int number;

cin >> number;

char firstCharacterOfNames;
cin >> firstCharacterOfNames;  // This will discard all leading white space.
                               // including new-line if there happen to be any.

cin.unget();                   // Put back the first character of the name.

std::string  names;
std::getline(cin, names);      // Read the names;

または。あなたが知っているなら、番号と名前は常に異なる行になります。

cin >> number;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
std::getline(cin, names);
于 2011-04-21T08:47:58.947 に答える
7

getlineを使用する前に、std :: wsを使用して、入力バッファー内の空白文字を抽出できます。std::wsのヘッダーはsstreamです。

cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
cin>>ws;
getline(cin, names);
于 2015-04-16T17:50:21.657 に答える
6

getline()関数の前にcinを使用する場合は、cin.ignore()を試してください。

void inputstu(){
    cout << "Enter roll Number:";
    cin >> roll_no;
    cin.ignore(); //ignore the withspace and enter key
    cout << "Enter name:";
    getline(cin, stu_name);
}
于 2018-12-09T16:09:43.400 に答える
1

または、入力バッファをフラッシュして文字列を読み取ることができます

fflush(stdin)

ヘッダーstdio.hで定義されています。

このコードは機能します。

cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;
fflush(stdin);  //FLUSHING STDIN
getline(cin, names);
于 2016-09-12T13:17:18.843 に答える
1

使ったばかり

getline(cin >> ws,lard.i_npute);

標準で

#include <iostream>

キャリッジリターンに問題があり、wsマニピュレーターが機能した場合のヘッダー。おそらく、ループ関数をクラスとして埋め込み、少なくともコンストラクタとデストラクタの呼び出しを使用し始めます。

于 2016-10-27T17:25:31.413 に答える
1
cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;
getline(cin, names);//works on the \n left behind
getline(cin, names);//continues and rewrites names

そのかなり自明で、\ nを使用するストリームに残されてcin >> numberおり、これは最初に使用されたときに名前に割り当てられます。getlineを再利用すると、正しい値が書き込まれるようになります。

于 2018-03-19T17:11:05.620 に答える
0

あなたはcppreferenceであなたが望む答えを見つけることができます。

空白で区切られた入力の直後、たとえば後int n; std::cin >> n;などに使用すると、getlineは演算子>>によって入力ストリームに残されたエンドライン文字を消費し、すぐに戻ります。cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');一般的な解決策は、行指向の入力に切り替える前に、入力行に残っているすべての文字を無視することです。

于 2016-08-20T02:17:39.983 に答える
0

cinでint変数を取得した後、バッファに残っている「\ n」を無視したいので、cinステートメントの後にcin.ignore()を使用します。

私は私が同様の問題で使用した同様のプログラムを持っています:

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    // Declare second integer, double, and String variables.
    int n;
    double d2;
    string str;

    // Read and save an integer, double, and String to your variables.
    cin >> n;
    cin >> d2;

    cin.ignore();

    getline(cin, str);

    // Print the sum of both integer variables on a new line.
    cout << i + n << endl;


    // Print the sum of the double variables on a new line.
    cout << d + d2 << endl;

    // Concatenate and print the String variables on a new line
    cout << s << str << endl;

    // The 's' variable above should be printed first.

    return 0;
}
于 2016-09-16T18:49:15.640 に答える
0

概念的には、それぞれの答えを1行にまとめてほしいと思います。では、これを試してみませんか?

cout << "Enter the number: ";
string line;
getline(cin, line);
int number = std::stoi(line);

cout << "Enter names: ";
string names;
getline(cin, names);

コードは最初の改行文字を正しく消費し、行が正しい場合は番号を示し、正しくない場合は例外をスローします。すべて無料です!

于 2017-11-09T12:56:45.253 に答える
-1
#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "Enter the number: ";
    int number;
    cin >> number;
    cout << "Enter names: ";
    string names;

    // USE peek() TO SOLVE IT! ;)
    if (cin.peek() == '\n') {
        cin.ignore(1 /*numeric_limits<streamsize>::max()*/, '\n');
    }

    getline(cin, names);

    return 0;
}

を使用して先を確認し、の内部バッファにcin.peek()a'\n'がまだ残っているかどうかを確認してください。cinもしそうなら:それを無視します(基本的にそれをスキップします)

于 2015-02-03T09:55:03.603 に答える