C + + structure array + cycle simple example 1

C + + structure array + cycle simple example 1

Take notes for yourself.


Each customer is assigned a customer number (starting from 0), and an array is defined to record the purchase amount of each customer every day. The index of the array exactly corresponds to the customer number. After receiving the last customer of the day, output the customer number and purchase amount of each customer, the total purchase amount and the average purchase amount of each customer.


  1. Define array;
  2. Customer, customer number and purchase amount;
  3. One customer corresponds to one customer number, and the purchase amount is overlapped;
  4. Infinite circulation until the store is closed (i.e. the purchase amount is 0);
  5. Input and output are readable;

1. Define structure array

using namespace std;
struct Customer
 char name[10];
 int num;
Customer cus[100];

2. Enter name and amount
*Note that a name corresponds to a customer number

int main()
 int i=0,j=0,num;
 char name[10];
 float parchase[100],money;
 while(true)  //Infinite loop. Multiple customers can be entered 
  cout<<"the total price is ";
  if(money==0)  //Cycle stop condition, store closed 
  cout<<"the customer's name is ";
  for(j=0;j<=i;j++)  //Loop to compare with previously saved names 
   if(0==strcmp(cus[j].name,name))  //Judge whether there is repetition with the previous cycle 
    cout<<"the number of "<<cus[j].name
     <<" is "<<cus[j].num<<"\n";
    cout<<"the parchase is "<<parchase[j]<<"\n"<<endl;
   else if(j==i)  //Cycle to the last time and still don't find that the name has been saved, save the name in the new customer number 
    cout<<"the number of "<<cus[i].name<<" is "<<cus[i].num<<"\n";
    cout<<"the parchase is "<<parchase[i]<<"\n"<<endl;
    break;  //There will be mistakes if you don't jump out 

3. output
It's ok to sum the average value of each customer in a very simple circular output

 float sum=0,ave;
  cout<<"today's the parchase is"<<endl;
   cout<<"["<<cus[j].num<<"]"<<cus[j].name<<":"<<parchase[j]<<"Yuan; ";
 cout<<"the total is "<<sum<<"element."<<endl;
 cout<<"the average is "<<ave<<"element."<<endl;
  cout<<"No guest today."<<endl;

The results are as follows:


-Determine whether two character arrays are identical

strcmp(const char *s1,const char *s2)

-Infinite cycle
Set conditions, break out

-Assignment of character array

strcpy(str1,str2)  //Assign str2 to str1

Note: in this question, assigning the name of string type to character array will report an error for unknown reasons;
(personal doubt is that the input name length is uncertain, and the system is not sure whether the character array can hold, so an error is reported.)
But you can assign the character array name to the character array.

Another: the output of this solution is not a big problem, but the logic is not optimized.

Posted by franck on Tue, 03 Dec 2019 08:30:51 -0800