Looping array?

Hi, this will be my 4th time to post question in this forum. Currently, I am facing a problem with getting a string to store. Let say that I write a program of mathematics quiz. The program prompt for number of user. And if the program has received 3 as number of user, then the program need to ask for the user's name. How can I write the program part for this? I had tried with array, but it came out with certain alphabets. What type of code should I used for this?

Sample output is as follows:
Please enter number of participants (1-5): 3
Please enter name 1: Henry Darren
Please enter name 2: Peter Pretelli
Please enter name 3: Sharon Williams

I know that this part suppose to be using loop. But how can I store those names in string? Any idea? And can I use structure in this case?
A vector would be easier, but I suppose you haven't learned that yet?
Anyway, something like this would do. Although I'm sure there are way better ways to do this.

PS: Can't test the code I'm on vacation so...

1
2
3
4
5
6
7
8
9
10
11
12
13
int x;
string person[y];

cout<<"How many people would you like to enter?";
cin>>x;
EmptyBuffer; // You should make a simple function for this


for (int y = 0; y < x; ++y)
{
cout<<"enter person"<< y + 1;
getline(cin, person[y])
}


Before you try it, I am absolutely not sure you can make an array of strings...
Yes you can make an array of streams and yes a vector of strings would be better.
Can I know what header should I include in order to make the code move?

And, how can I get the value out to use it in another function, assume that this is one of the sub function of the program.
#include <string>

And, how can I get the value out to use it in another function, assume that this is one of the sub function of the program.

Do you mean passing the array to a function? Or passing one of the elements to a function?
passing the array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>

void display(std::string *array, int num) {     
     for(int i=0; i<num; ++i) {
        std::cout << '\n' << *array++;
     }
     return;
}

int main()
{
    int num = 0;
    
    std::cout<<"How many people would you like to enter? ";
    std::cin>>num;
    std::cin.ignore();
    
    std::string *names = new std::string[num];
    
    for (int i = 0; i < num; ++i) {
      std::cout<<"enter person "<< i + 1 << ": ";
      getline(std::cin, names[i]);
    }

    display(names, num);

    delete names;
    
    std::cin.get();
    return 0;
}
Last edited on
thanks for those info.. it works.. thank you very much..
Topic archived. No new replies allowed.