如何解决输入从指针接受空格时出现问题
我试图用我的名字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;
}
解决方法
此声明之后
cin >> i->score;
输入缓冲区包含与按下的Enter键相对应的换行符'\n'
。
因此,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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。