how to pass an array of string type ?

hello,
I've faced a problem while solving my assignment, hope to find a help .
I want to know how to read a string from a file , then pass it through a function !
knowing that this string is (two string as first and last names separated by spaces )

this is the file :
Ali Alabri
Salem Alalawi
Mouza Alrawahi
Sultan Altuqi
Dhahi Alnoubi
Tannaf Albarwani
Masood Albalushi
Saleem Aljahwari
Sameera Alazani
Zoulikha Alfazari

and here what I did :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include<iostream>
#include<string>
#include<fstream>
using namespace std ;

int main ()
{
	string name[5][2];
	ifstream input;
	input.open("cosumersName.txt");
	
	for(int i=0 ; i<5 ; i++ )
		{
			for ( int c=0 ; c<2 ;c++ )
	{
		input >> name[i][c];
	    cout << name[i][c];
	}
		cout << endl;
	}
		return 0;
}



I did not pass through a function yet , I wanted to try how to read these strings !
should we use two dimensional array ?
Last edited on
A couple of problems:
1) You have 10 rows in your list, but have only allocated space for 5.
2) You read only 5 pairs. You should be reading until end of file.

As for calling a function, you haven't indicated what you want the function to do. You have two choices when designing the function.
1) You can pass the full array to the function, or,
2) You can pass one row at a time to the function
Which you choose depends on what you want the function to do.

Option 1:
1
2
3
4
5
 
void func (string & name[5][2])
{ ... }

  func (name);  // Call and pass full array 


Option 2:
1
2
3
4
void func (string firstname, string lastname)
{ ... }

  func(name[i][0], name[i][1]);  // call and pass name pair 


You should really be using a vector container which will allow you add any number of name pairs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>
#include <string>
using namespace std;

struct customer
{  string first name;
    string last_name;
    // other customer information
};

vector <customer> customers;
customer temp;

//  In your read loop
  input >> temp.first_name >> temp.last_name;
  customers.push_back (temp);
Got it !
thank you .
Topic archived. No new replies allowed.