Like Tree1Likes
  • 1 Post By MacNilly

C++ program problem..

This is a discussion on C++ program problem.. within the C++ Programming forums, part of the General Programming Boards category; Hey everyone. Got a question again that I've been racking my brain on trying to fix it and I haven't ...

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    13

    C++ program problem..

    Hey everyone. Got a question again that I've been racking my brain on trying to fix it and I haven't been able to yet. The program listed below has to do most of what the functions I have set say they do like get the highest balance, print the array, so on and so forth. I have a struct that has a double balance that seems to work fine when I use the function for highest balance but I get crazy math with the totalBalance function. For whatever reason I keep getting what i guess is a memory address or something. I have no idea why as everything else seems to work smoothly. If anyone could help me out I appreciate it. Any other advice on the program too is appreciate.

    Oh. Also I have to print out something like student name, balance for the person with the highest balance. I know how to find the highest balance but really I'm lost on trying to use that to access the string name for that element. Thanks in advance.

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    //set constant for array size
    const int SIZE = 100;
    
    //declaring struct and it's variables
    struct studentInfo {
    	int studentAnumber;
    	string studentName;
    	double balance;
    };
    
    //Prototypes for functions
    void getInfo(studentInfo student[], const int SIZE, int &count);
    
    void searchString(studentInfo student[], int &count, int &leng);
    
    void highestBalance(studentInfo student[], int &count, double &high);
    
    void totalBalance(studentInfo student[], int &count, double &total);
    
    void printArray(studentInfo student[], int &count, int &leng);
    
    int main() {
    	
    	//declare array for struct studentInfo and initialize to constant size
    	studentInfo students[SIZE];
    	
             cout << "Welcome to the student account manager!" << endl;
    	
    	//declare and initialize counter variable and call function to get                                                                                         information input into array
             int counter = 0;
    	getInfo(students, SIZE, counter);
    
    	//call function to determine the length of the longest studentName in the array
            int length;
            searchString(students, counter, length);
    
    	cout << "Length is now " << length << endl;
    
    	//call function to determine the highest balance
            double highestBal;
            highestBalance(students, counter, highestBal);
            cout << "highest balance is " << fixed << showpoint << setprecision(2) << highestBal << endl;
    	
           //call function to determine the total balance
           double totalBal;
           totalBalance(students, counter, totalBal);
           cout << "the total balance is " << fixed << showpoint << setprecision(2) << totalBal << endl;
    
    
    	cout << "Report" << endl;
    	cout << "------" << endl;
            cout << "A-NUMBER" << "    " << setw(length) << "NAME" << "BALANCE" << endl;
    
    	printArray(students, counter, length);
    
        system("Pause");
    	return 0;
    }
    
    void getInfo(studentInfo student[], const int SIZE, int &count) {
    	
    	for(int i = 1; i < SIZE + 1; i++) {
    			//Ask user for A number, check for valid input
    			cout << "Enter student " << i << " A number (or -999 to exit): ";
    			cin >> student[i].studentAnumber;
    			if (student[i].studentAnumber == -999) {
    					break;
    			}
    			count = count + 1;
    			while (cin.fail()) {
    					cin.clear();
    					cin.ignore(100,'\n');
    					cout << "Invalid input. Please enter a valid A number: ";
    					cin >> student[i].studentAnumber;
    				}
    			cin.ignore();
    			//Ask user for student name. Getline for string
    			cout << "Enter student " << i << " name: ";
    //			cin >> students[i].studentName;
    			getline(cin, student[i].studentName);
    			
    			//Ask user for balance, check for valid input
    			cout << "Enter student " << i << " balance: ";
    			cin >> student[i].balance;
    				while (cin.fail()) {
    					cin.clear();
    					cin.ignore(100,'\n');
    					cout << "Invalid input. Please enter a valid balance: ";
    					cin >> student[i].balance;
    				}
    			cout << endl;
    		}
    	
    }
    
    void searchString(studentInfo student[], int &count, int &leng) {
    
    	leng = student[0].studentName.length();
    
    	for(int i = 0; i < count; i++) {
            if ( student[i].studentName.length() > leng ) {
                leng = student[i].studentName.length();
    		}
    	}
    }
    
    
    void highestBalance(studentInfo student[], int &count, double &high) {
    
    	double temp = 0;
    	
    	for(int i = 0; i < count; i++) {
            if ( student[i].balance > temp ) {
                temp = student[i].balance;
                high = temp;
            }
       }
    
    }
    
    void totalBalance(studentInfo student[], int &count, double &total) {
    
    	double temp = 0;
    
    	for(int i = 0; i < count; i++) {
    		temp = temp + student[i].balance;
    		total = temp;
            }
    }
    
    void printArray(studentInfo student[], int &count, int &leng) {
    	
    	for(int i = count; i > 0; i--) { 
    		cout << student[i].studentAnumber << "  " << setw(leng) << student[i].studentName << student[i].balance << endl;
    	}
    }

  2. #2
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Being C++, you should be taking advantage of the STL and what it has to offer. Something like the following should get you going in the right direction:
    Code:
    #include <iostream>
    #include <string>
    /*use STL to simplify life*/
    #include <vector>
    #include <algorithm>
    #include <iterator>
    
    struct studentInfo{
    	std::string name;
    	double accountBalance;
    };
    
    void getInfo(std::vector<studentInfo>&);
    bool compare(studentInfo,studentInfo);
    
    int main(void){
    
    	//Use a vector vice array here
    	std::vector<studentInfo>studentArray;
    	std::vector<studentInfo>::iterator ii;
    	//Get student info
    	getInfo(studentArray);
    	//sort vector based on account balance
    	std::sort(studentArray.begin(),studentArray.end(),compare);
    
    	//Print out sorted vector
    	for(ii=studentArray.begin();ii!=studentArray.end();++ii){
    		std::cout<<ii->name <<" "<<ii->accountBalance << std::endl;
    	}
    
    
    	return(0);
    }
    void getInfo(std::vector<studentInfo>& studentvect){
    
    	studentInfo currentStudent;
    	std::string answer;
    	do{
    		std::cout<<"Enter name: ";
    		std::cin >>currentStudent.name;
    		std::cout<<"Enter balance: ";
    		std::cin>>currentStudent.accountBalance;
    		studentvect.push_back(currentStudent);
    		std::cout<<"Continue(yes or no)";
    		std::cin>>answer;
    	}while(answer=="yes");
    }
    bool compare(studentInfo student1, studentInfo student2){
    
    	return (student1.accountBalance < student2.accountBalance);
    }
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  3. #3
    Registered User
    Join Date
    Feb 2011
    Posts
    13
    I'd love to use vectors and all but the teacher wants an array. It seems much simpler what you've written and makes sense but I have to stick to basically the format with the functions and array that I have

  4. #4
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    Quote Originally Posted by Fandango21 View Post
    I'd love to use vectors and all but the teacher wants an array. It seems much simpler what you've written and makes sense but I have to stick to basically the format with the functions and array that I have
    If that's the case, it may be a good prank to write your own vector class(syntactically similar to std::vector...so the code remains portable) which uses arrays internally and use it in every opportunity you get !
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  5. #5
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Posts
    311
    I'm feeling generous. I fixed your code (somewhat) but I will tell you what you had wrong so you know in the future.

    2 main problems: using reference parameters when you have no intention of changing their values is BAD. Use pass-by-value or const references. That way you avoid hard to find bugs.

    The other is not using the (int i = 0; i < N; ++i) idiom; not using it is a good way to get off-by-one errors which you had.

    Other than that, the program is well-coded.

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <cstdlib> // for system()
    
    using namespace std;
    
    //set constant for array size
    const int SIZE = 100;
    
    //declaring struct and it's variables
    struct studentInfo {
    	int studentAnumber;
    	string studentName;
    	double balance;
    };
    
    //Prototypes for functions
    
    /** CHANGED **/
    void getInfo(studentInfo student[], int size, int &count);
    
    /** CHANGED **/
    void searchString(studentInfo student[], int count, int &leng);
    
    /** CHANGED **/
    void highestBalance(studentInfo student[], int count, double &high);
    
    /** CHANGED **/
    void totalBalance(studentInfo student[], int count, double &total);
    
    /** CHANGED **/
    void printArray(studentInfo student[], int count, int leng);
    
    int main() {
    
    	//declare array for struct studentInfo and initialize to constant size
    	studentInfo students[SIZE];
    
             cout << "Welcome to the student account manager!" << endl;
    
    	//declare and initialize counter variable and call function to get                                                                                         information input into array
             int counter = 0;
    	getInfo(students, SIZE, counter);
    
        cout << "Counter is " << counter << endl;
    	//call function to determine the length of the longest studentName in the array
            int length;
            searchString(students, counter, length);
    
    	cout << "Length is now " << length << endl;
    
    	//call function to determine the highest balance
            double highestBal;
            highestBalance(students, counter, highestBal);
            cout << "highest balance is " << fixed << showpoint << setprecision(2) << highestBal << endl;
    
           //call function to determine the total balance
           double totalBal;
           totalBalance(students, counter, totalBal);
           cout << "the total balance is " << fixed << showpoint << setprecision(2) << totalBal << endl;
    
        system("pause");
    	cout << "Report" << endl;
    	cout << "------" << endl;
            cout << "A-NUMBER" << "    " << setw(length) << "NAME" << "BALANCE" << endl;
    
    	printArray(students, counter, length);
    
        system("Pause");
    	return 0;
    }
    
    void getInfo(studentInfo student[], int size, int &count) {
    
    	for(int i = 0; i < size; i++) { // <-- always do this way (avoids off by one errors)
    			//Ask user for A number, check for valid input
    			cout << "Enter student " << i+1 << " A number (or -999 to exit): ";
    			cin >> student[i].studentAnumber;
    			if (student[i].studentAnumber == -999) {
    					break;
    			}
    			count = count + 1;
    			while (cin.fail()) {
    					cin.clear();
    					cin.ignore(100,'\n');
    					cout << "Invalid input. Please enter a valid A number: ";
    					cin >> student[i].studentAnumber;
    				}
    			cin.ignore();
    			//Ask user for student name. Getline for string
    			cout << "Enter student " << i << " name: ";
    //			cin >> students[i].studentName;
    			getline(cin, student[i].studentName);
    
    			//Ask user for balance, check for valid input
    			cout << "Enter student " << i << " balance: ";
    			cin >> student[i].balance;
    				while (cin.fail()) {
    					cin.clear();
    					cin.ignore(100,'\n');
    					cout << "Invalid input. Please enter a valid balance: ";
    					cin >> student[i].balance;
    				}
    			cout << endl;
    		}
    
    }
    
    void searchString(studentInfo student[], int count, int &leng) {
    
    	leng = student[0].studentName.length();
    
    	for(int i = 1; i < count; i++) {
            if ( student[i].studentName.length() > leng ) {
                leng = student[i].studentName.length();
    		}
    	}
    }
    
    
    void highestBalance(studentInfo student[], int count, double &high) {
    
    	high = student[0].balance;
    
    	for(int i = 1; i < count; i++) {
            if ( student[i].balance > high ) {
                high = student[i].balance;
            }
       }
    }
    
    void totalBalance(studentInfo student[], int count, double &total) {
        total = 0;
    	for(int i = 0; i < count; i++) {
    		total += student[i].balance;
            }
    }
    
    void printArray(studentInfo student[], int count, int leng) {
    
    	for(int i = 0; i < count; ++i) {
    		cout << student[i].studentAnumber << "  " << setw(leng) << student[i].studentName << student[i].balance << endl;
    	}
    }
    AndrewHunter likes this.
    GCC on Fedora Core 10

  6. #6
    Registered User
    Join Date
    Feb 2011
    Posts
    13
    Thanks for mentioning the constant references, I forgot and they will definitely help avoid future confusion and bugs. I found my off by one error only like 10 minutes ago. Wish I would have remembered I changed that in the getInfo function. As for the (int i = 0; i < N; ++i), That's all we've used up to this point so I don't know of another method to cycle through things. What would you suggest using instead? I appreciate the help and I'm still plugging along trying to get better so I definitely take any advice I can get. Also, any suggestions on my second problem? I still have no clue how to go about it. I have the highestBalance function that finds the highest balance in the array of structs but I also need to get the string Name of that same element in the array and output it like this. "The highest balance is : " John Doe " , $500.00. Thanks again!

  7. #7
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Instead of saving the highest balance, save the index in the array that contains the highest balance. Then you can just print out the information directly.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #8
    Registered User
    Join Date
    Feb 2011
    Posts
    13
    Thanks Andrew. That's what I just modified the highestBalance function to do. It returns the index and now I can use that outside to print what I needed. Thanks everyone for the help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. CS1 Program (New Problem)
    By DaNxTh3xMaNx in forum C Programming
    Replies: 3
    Last Post: 09-30-2010, 02:04 AM
  2. Replies: 4
    Last Post: 10-16-2008, 07:30 PM
  3. Math Equation Program (I can't find the problem with my program!)
    By masked_blueberr in forum C Programming
    Replies: 14
    Last Post: 07-06-2005, 11:53 AM
  4. Problem with a program...
    By brian85 in forum C++ Programming
    Replies: 3
    Last Post: 05-02-2005, 12:19 PM
  5. problem with my program
    By ArseMan in forum C++ Programming
    Replies: 3
    Last Post: 09-09-2001, 06:15 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21