C++ 输入从指针接受空格时出现问题

C++ 输入从指针接受空格时出现问题,c++,vector,C++,Vector,我试图在我的名字char中接受空格,但每次我在输入(在int main中询问)我想输入多少分数后运行程序时,它就会出错,并同时提示两个输入。如有任何帮助/建议,将不胜感激 void readData(vector<Highscore>& scores) { //Local integer variable used to update user # int index = 0; //For loop iterator that stores user

我试图在我的名字char中接受空格,但每次我在输入(在int main中询问)我想输入多少分数后运行程序时,它就会出错,并同时提示两个输入。如有任何帮助/建议,将不胜感激

void readData(vector<Highscore>& 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;
}
void readData(向量和分数)
{
//用于更新用户的局部整数变量#
int指数=0;
//存储用户输入和名称的For循环迭代器
对于(向量::迭代器i=scores.begin();i!=scores.end();i++)
{
//提示用户输入名称
我不能->名字;
//提示用户输入他们的分数
cout评分;
//跟踪索引并在每次迭代时更新它
索引++;
} 
在这句话之后

cin >> i->score;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
cin >> i->score;
输入缓冲区包含与按下的Enter键对应的新行字符
'\n'

因此,
std::getline
的下一个调用读取一个空字符串

您需要在调用
std::getline
之前删除它

您可以通过插入此语句来执行此操作

cin >> i->score;
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;
}
#包括
#包括
#包括
int main()
{
std::字符串s;
字符c;
做
{

std::cout在调用getline之前插入此语句std::cin.ignore(std::numeric_limits::max(),'\n');