transferring contents from 1D array into a 2D arrray

how can you transfer contents of a 1D array into a 2D array as in; if the sentence "i am a good boy" is stored in a 1D array text[50] then it should be transferred into a 2D array text2[50][50]={"i","am","a","good","boy"}

i have written the following code but it isnt working..... plz suggest somethin....
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
#include<stdio.h>
#include<conio.h>
main()
{
char text[50],text2[50][50];int i=0,j=0,k=0;
printf("enter a text ");//to enter the contents of the 1D array text
gets(text);
while(text[i]!='\0')//to put the contents into the 2D array
{	if(text[i]==' ')
	{
   j++;k=0;
   }
   else
   {
	text2[j][k]=text[i];
   }
i++;
}
j=0;k=0;
while(text2[j][k]!='\0')//to print the contents of the 2D array
{

   while(text2[j][k]!='\0')
   {
	printf("%c",text2[j][k]);
   k++;
   }
j++;k=0;
}
getch();
}
Last edited on
In my opinion the simplest way is to write a function or a macro that skips blank characters. For example

#define SkipSpaces( p ) while( isspace( p ) ) ++p


and use it in your code.

Also it would be a good idea to init your 2D array with zeroes.

char text[50],text2[50][50] = { '\0' };
Last edited on
1
2
3
4
5
6
7
enum { N = 50 } ;
char text2[N][N] = { {0} } ;
const char text[] = "i am a good boy" ;

std::istringstream stm(text) ; // #include <sstream>
int nwords = 0 ;
while( nwords<N && stm.getline( text2[nwords], N, ' ' ) ) ++nwords ;

@JLBorges,
Taking into account names of headers and the using of function gets it seems that the code is written on C not C++.
Last edited on
@vlad ur right but since its the precursor to c++ it wont matter really....can you figure it out

Topic archived. No new replies allowed.