Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C++ getline problem using a string in an array of structs

Options
  • 30-01-2010 5:19pm
    #1
    Registered Users Posts: 12,683 ✭✭✭✭


    Something I've done in this small app is screwy, and I'm stumped. It should run the loop 3 times, each time reading in the string, and the two sets of floats, then print it all out at the end. It only reads the string in once though, any pointers?
    #include <iostream.h>
    #include <stdlib.h>
    #include <string>
    #define Length 3
    
    struct PersInfo
    {
    string strName;
    float fltBalance;
    float fltInterest;
    } PersInfo [Length];
    
    int main ()
    {
    
    for (int n=0; n<Length; n++)
    {
    cout << "Input Name ";
    getline (cin,PersInfo[n].strName);
    cout << "Input Balance ";
    cin >> PersInfo[n].fltBalance;
    cout << "Input Interest ";
    cin >> PersInfo[n].fltInterest;
    cout << "\n";
    }
    
    cout << "\n" << "\nDisplaying the contents of the array of structs\n" << "\n";
    
    for (int n=0;n<Length; n++)
    {
    cout << "Name " << PersInfo[n].strName << "\nBalance " << PersInfo[n].fltBalance << "\nInterest " << PersInfo[n].fltInterest <<"\n" << "\n";
    }
          system("PAUSE");
          return 0;
    }
    

    Turns out it's a buffer problem with Dev C++, you need to put the following line in before the getline command to flush it out :
    cin >> ws;
    


Advertisement