Cin in arrays within for loop

Hello!
How can i use cin in an array ?
I want to store more names in an array within a for loop.


I tried this but it didn't work....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main (){
	
int a;
char *Name[5];
for(a = 0;a<5;a++) {
cin>>Name[a];
	
	}
	
system("pause");
	return 0;
}

I want that after the for loop,the "Name" char should look something like this :

 
char *Name[5]={"example 1","example 2","example 3","example 4","example 5"}
Last edited on
You have to define a two-dimensional array of type char. For example

1
2
3
4
5
6
const int ROWS = 5;
const int COLS = 10;

char Names[ROWS][COLS]

for ( int i = 0; i < ROWS; i++ ) std::cin >> Names[i];



You should take into account that the input for a given element (row) for the array shall not exceed COLS - 1 chracters.
Otherwise it is better to use standard C++ class std::string.
Last edited on
thank you,it works now :)

#closethread
One more question :
How can I ask the user the size of the array(ROWS)?
@Guzfraba

Here's how I do it..

1
2
3
4
int maxSize;
cout << endl << "Maximum size for the array, equal to what ? : ";
cin >> maxSize;
int* arr = new int[maxSize]; //Rename arr to array name to desire 
@whitenite1

please tell me how to use this:
1
2
3
4
int maxSize;
cout << endl << "Maximum size for the array, equal to what ? : ";
cin >> maxSize;
int* arr = new int[maxSize]; //Rename arr to array name to desire  

in this structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main (){
	
const int ROWS = 5;
const int COLS = 10;

char Names[ROWS][COLS];

for ( int i = 0; i < ROWS; i++ ) {
	cin >> Names[i];
}

	
	
	
system("pause");
	return 0;
}


I tried many times but i got just errors :(
The user should write the value of ROWS,COLS should remain 10.
Thank you :)
@Guzfraba

Well, to get it to work, I had to change char to string. You can write code to have the user re-type a name if its length is longer than COLS.
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
// New array.cpp : main project file.

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main ()
{

	int maxSize;
	cout << endl << "How many names are there ? : ";
	cin >> maxSize;
	
	const int ROWS = maxSize;
	string* Names = new string[ROWS]; 

	for ( int i = 0; i < ROWS; i++ )
	{
		cout << "Please enter name number " << i+1 << " : ";
		cin >> Names[i];
	}
	cout << endl << "You entered these " << ROWS << " names.." << endl;
	for ( int i = 0; i < ROWS; i++ )
	{
		cout << Names[i] << endl;
	}
	system("pause");
	return 0;
}
thank you,it works now :D
Topic archived. No new replies allowed.