How to answer a question in each loop?

Hi! I am new to programming and C++ so if you can pls help me.

I have a question loop code that prints only up to five:

for(int i = 0;i < 5;i++)
{
cout << "What is your name?" << endl;
}

So my problem is how can I cin some names for each question that I looped?
closed account (48T7M4Gy)
1
2
3
4
5
6
7
string name[5];

for(int i = 0;i < 5;i++)
{
     cout << "What is your name?" << endl;
      cin << name[k];
}


You might have to fix a couple of errors but that's about it.
Thank you for the reply! It helped me a lot.
Hey jeromepab,

I don't know if I completely understood you want to do, but here is how you can ask to input 5 names. You need to create a string typed fixed array with a size of 5 that will hold a name on each element. Note you will need the string header for this (#include <string>).

1
2
3
4
5
6
7
std::string names[5];

for(int i = 0;i < 5;i++)
{
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, names[i]);
}


This will ask the user to input a name 5 times, and the names will be stored in the array. You can then access the array with [ ] operator, such as: names[2], and it will return whatever name the user entered in the 3rd input.

You can also print all the names with a for loop:

1
2
for (auto &element : names)
    std::cout << element << "\n";
Hi SideEffects,

I'm sorry but I'm just a student who's studying the basics of C++ and our professor hasn't teach us about std:: so I'm slightly confused on your code,but still I think I got your point.Thanks for the reply anyway, greatly appreciate it.
That means you're most likely using using namespace std;

Imagine it like this: you have a lab-sized workspace, and you have a shelf named "std" with a whole bunch of stuff on it, cin and cout being two of them. You call cout to output a bit of text, meaning you've grabbed a copy of that method off the shelf to use.

What using namespace std; does for you is put that entire shelf inside your workspace. What std:: does for you is basically going out of the workspace to get that one specific item, like cout, from another storage room.
Ohh I see, thanks for the additional information YFGHNG,helps me on my studies.
Topic archived. No new replies allowed.