简体   繁体   中英

C++ Don't enter in my cin

I have a little problem that i don't understand. I have try a lot of things that i read on internet but nothing actualy work.

My main.cpp code :

#include <iostream>
using namespace std;
#include "Equipe.h"
#include "Club.h"

//PROTOTYPE
void MenuSecClub();
void MenuSecFed();


int main(int argc,char* argv[])
{
    int choice;
    //cout << " Welcome heeere !!!" << endl;
    Club C;
    cin >> C;
    cout << " hello : " << C;
    cin >> choice;
    return 0;
}

My Club istream code

istream& operator>>(istream& s,Club& C)
{
    int nc;
    char Buffer[20],Buffer2[20];
    cout << "Enter a name" << endl;
    s.getline(Buffer,20);
    C.setNom(Buffer);
    s.clear();
    cout << "Enter a num club" << endl;
    cin >> nc;
    C.setNumClub(nc);
    s.clear();
    cout << "Enter the address of the club" << endl;
    s.getline(Buffer,20);
    C.setAdresse(Buffer);
    s.clear(); 

    return s;   
}

The first two cin work fine ( the Name and the NumClub) and when he arrives in the cin for the address it passes in and passes directly in the cout of the main. I can't write anything for the address.

I have try the clear, i have try a second buffer for the getline. I don't understand what happend.

Thanks for your help !

You have several issues here:

  1. cin >> nc does not remove the trailing end line from the stream. So the next s.getline(Buffer,20) actually reads this \\n character and therefore exits before anything else is typed in.

  2. It seems that you think s.clear() clears the remaining content of the stream, but that is not the case. It just resets the flags. This is why the \\n is still in the stream.

  3. cin >> nc only parses matching input. So if someone does not enter a number, it will still be in the stream together with the \\n.

  4. Using a single operator>> call for requesting multiple inputs from the user is very unusual, because it is an unexpected side effect. Think about someone using the operator>> to read from a file stream. That would be strange...

My proposal: Instead of using an operator>>, create a member function in Club called for example "fillFromStdin()". Better would be a dedicated factory, but that is ok for the start. Then avoid mixing getline and the >> operator. This has some ugly side effects . Better use getline only and then parse the input afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM