getline(cin, str)
默认读入字符,直到回车停止
其实等价于getline(cin, str, ‘\n’)
而getline(cin, str, ‘,’)表示读入字符,直到逗号为止
如果使用getline(cin, str, ‘,’)的话,就要注意上一行的回车的问题
这种情况,输入的1之后还有一个'\n'
getline的时候也读入了进来,所以str的内容实际上是
"\nabc" 所以输出的时候就会先输出一个空行然后输出abc
怎么解决这个问题?
可以在cin后加一个getchar()吞掉回车,这样这个回车就不会读到str里面
如图,这样输出的结果就是正确的,不会先输出一行
当前一输入的是字符串的时候,还有另外一种解决方法
两者唯一的区别是前者用cin 后者用 getline 而后者的结果是正确的
用cin的话,上一行的回车还没读入
用getline的话,回车读入了,但是这个回车没有在字符串a中
和getline(cin, b, ',')中逗号不在b字符串中是一样的
理解了之后AC这道题就很容易了
#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = (a); i < (b); i++)
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;
class CBook
{
string name, editor, press;
double price;
public:
CBook() {}
CBook(string a, string b, double c, string d): name(a), editor(b), price(c), press(d) {}
friend istream& operator >> (istream& in, CBook& c);
friend ostream& operator << (ostream& out, const CBook& c);
friend void find(CBook *book, int n, int &max1index,int &max2index);
};
istream& operator >> (istream& in, CBook& c)
{
getline(in, c.name, ',');
getline(in, c.editor, ',');
string str; getline(in, str, ',');
c.price = stod(str); //stod是string转double
getline(in, c.press); //最后这里用getline而不是in
return in; // getline可以读入这一行的回车从而这个回车不干扰到下一行
}
ostream& operator << (ostream& out, const CBook& c)
{
cout << c.name << endl;
cout << c.editor << endl;
printf("%.2f\n", c.price);
cout << c.press << endl << endl; //注意这里要输出两个回车,题目输出格式要求
return out;
}
void find(CBook *book, int n, int &max1index,int &max2index)
{
double mx = 0;
rep(i, 0, n)
if(mx < book[i].price)
{
mx = book[i].price;
max1index = i;
}
mx = 0;
rep(i, 0, n)
if(i != max1index && mx < book[i].price)
{
mx = book[i].price;
max2index = i;
}
}
int main()
{
int T; cin >> T;
while(T--)
{
int n; cin >> n; getchar(); //吞掉n后的回车
CBook *book = new CBook[n];
rep(i, 0, n) cin >> book[i];
int max1index, max2index;
find(book, n, max1index, max2index);
cout << book[max1index] << book[max2index];
}
return 0;
}