C++ getline

来源:百度知道 编辑:UC知道 时间:2024/09/23 05:02:19
代码如下(VS2005运行):
//introducing the vector template
#include <iostream>
#include <string>
#include <vector>

const int NUM = 5;

int main()
{
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

vector<int> ratings (NUM);
vector<string> titles (NUM);
cout<<"You will do exactly as told. You will enter\n"
<<NUM<<" book titles and your ratings (0-10).\n";
int i;
for (i = 0; i < NUM; i++)
{
cout<<"Enter title #"<< i + 1 <<": ";
getline(cin, titles[i]);
cin.ignore();
cout<<"Enter your rating (0-10): ";
cin>>ratings[i];
cin.get();
}
cout<<"Thank you. You entered the following:\n"
<<"Rating\tBook\n"

把cin.ignore(); 去掉即可,修改如下:

//---------------------------------------------------------------------------

#include <iostream>
#include <string>
#include <vector>

const int NUM = 5;

int main()
{
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

vector<int> ratings (NUM);
vector<string> titles (NUM);
cout<<"You will do exactly as told. You will enter\n"
<<NUM<<" book titles and your ratings (0-10).\n";
int i;
for (i = 0; i < NUM; i++)
{
cout<<"Enter title #"<< i + 1 <<": ";
getline(cin, titles[i]);
//cin.ignore();
cout<<"Enter your rating (0-10): ";
cin>>ratings[i];
cin.get();
}
cout<<"Thank you. You entered the following:\n"