Hi, I’m new to c++ and am looking for some help. I’ve searched through most of the site but cant find exactly what I need, so thought I’d ask.
I need to read in strings (arrays of char) from a text file in a function then pass them back to the main. The code below does this but only for 2 strings. How do I go about changing the function to take arrays of strings, in other words 2d arrays of chars?

Thanks

#include <fstream>
#include <iostream>
#include<string.h>
using namespace std;
 
char get(char [], char[]);
int main()
{
char string1[6];
char string2[6];
get(string1,string2);
//print out 1st string
for(int w =0;w<6;w++)  
{
    cout<<string1[w];
}
cout<<endl;
//print out 2nd string
for(int e = 0; e<10;e++)
{
     cout<<string2[e];
}
int q;
cin>>q;
return 0;
}
char get(char string1[6], char string2[6])
{
ifstream fin("input.txt");
fin >> string1;
fin >> string2;
return 0;
}

you declare a 2d array of strings like this

const int ROWS = 255;
const int CHARS_PER_ROW  20

char array[ROWS][CHARS_PER_ROW];

then it looks like this

char get(char array[ROWS][CHARS_PER_ROW])
{
    ifstream fin("input.txt");
    if( fin.is_open())
    {
         int row = 0;
         while( row < ROWS && fin >> array[row++] )
            ;
   }
    return 0;
}

This link might help you understand a little more.

Thanks!

Another quick question if you don’t mind?

The txt file that I’m reading from has a list of names in it. When I print these from the array back in main I get a lot of nonsense after where the white space should have stopped the reading from the file.
After reading in the names dave and john I get this:

dave ,∞# á►$ john δ# ╔Uæ|(∩#

Any idea how I just get the names?

I’ve worked it out now so don’t worry about it!

ta

I’ve worked it out now so don’t worry about it!

ta

Yea I know all about that type of problem, I just spent three days trying to find one like that in my own program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.