Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

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

  • 30-01-2010 05:19PM
    #1
    Registered Users, Registered Users 2 Posts: 12,678 ✭✭✭✭


    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