Проблема с вводом, принимающим пробел из указателя

#c #vector

#c #вектор

Вопрос:

Я пытаюсь принять пробелы в моем имени char, но каждый раз, когда я запускаю программу после ввода (спрашивается в int main), сколько баллов я хотел бы ввести, она выдает ошибку и запрашивает два ввода одновременно. Любая помощь / предложения будут оценены.

 void readData(vector<Highscore>amp; scores)
{
    //Local integer variable used to update user #
    int index = 0;

    //For loop iterator that stores user input and name
    for(vector<Highscore>::iterator i = scores.begin(); i != scores.end(); i  )
    {
        //Prompts user for name
        cout << "Enter the name for score #" << (index   1) << ": ";
        cin.getline(i->name,'n');
        //cin >> i->name;

        //Prompts user for their score
        cout << "Enter the score for score #" << (index   1) << ": ";
        cin >> i->score;

        //Keeps track of the index and updates it everytime it iterates
        index  ;
    } 
    cout << endl;
}
  

Комментарии:

1. Перед вызовом getline вставьте эту инструкцию std::cin.ignore( std::numeric_limits<std::streamsize>::max(), ‘n’);

Ответ №1:

После этого утверждения

 cin >> i->score;
  

входной буфер содержит символ новой строки 'n' , который соответствует нажатой клавише Enter.

Итак, следующий вызов std::getline считывает пустую строку.

Вам нужно удалить его перед вызовом std::getline .

Вы можете сделать это, вставив этот оператор

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

после этого утверждения

 cin >> i->score;
  

Для этого вам необходимо включить заголовок

 #include <limits>
  

Попробуйте эту демонстрационную программу

 #include <iostream>
#include <string>
#include <limits>

int main() 
{
    std::string s;
    char c;
    
    do
    {
        std::cout << "Enter a string: ";
        std::getline( std::cin, s );
        std::cout << s << 'n';
        
        std::cout << "Continue ('y' to continue)? ";
        std::cin >> c;
        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );
    } while ( c == 'y' || c == 'Y' );
    
    return 0;
}