getline的输入问题

本文探讨了如何在C++中使用getline函数时避免因回车符导致的意外内容。通过实例说明了在cin和getline之间的区别,并提供了处理回车的方法,包括使用getchar()和理解getline行为。
摘要由CSDN通过智能技术生成

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值