Reputation: 633
I need a way to concat a string from a 2d array. I started off creating a 50x50 2d array initialized with blank spots (aka " ". Just spaces). Then I filled each line up using fgets and each line has a array of characters which form a string.
For example
H I T H E R E
H E L L O
W O R L D
and the empty spaces are kept as spaces.
Now, when I print it, I need to print "HI THERE HELLO WORLD" without all the spaces after each individual string since each row is 50 spots long.
Here's what I have so far.
void printArray(char matrix[arraySize][arraySize]){
int i,j;
int tempArrayCounter =0;
int tempArray[inputLineNumber * 50];
for(i = 0; i< arraySize; i++){
for(j = 0; j<arraySize;j++){
printf("%c,",matrix[i][j]);
}
printf("\n");
}
for(j=0; j< inputLineNumber;j++){
for (i = 0; matrix[i][j] != '\0'; i++){
tempArray[tempArrayCounter] =matrix[i][j];
tempArrayCounter++;
}
}
printf("%s\n", tempArray);
}
Ignore the first half of the function. All it does is show what the whole 50x50 2D array looks like.
Any help is appreciated. Thanks
EDIT
I'll add the code I used to fill the arrays if it helps.
void readInput(char matrix[arraySize][arraySize]){
//inputLineNumber is the current row of the input
inputLineNumber = 0;
/*
when the line is not empty, add the line into matrix
*/
char *p;
char currentline[arraySize];
fgets(currentline,arraySize, stdin);
if((p = strchr(currentline, '\n')) != 0){
*p = '\0';
}
while(strcmp(currentline, "\0")!=0){
int k;
int inputlength = (int)strlen(currentline);
for (k = 0; k< inputlength ;k ++)
matrix[inputLineNumber][k] = currentline[k];
fgets(currentline,arraySize, stdin);
if((p = strchr(currentline, '\n')) != 0){
*p = '\0';
}
inputLineNumber++;
}
}
Upvotes: 0
Views: 725
Reputation: 2026
You seem to be mostly on the right track, but you need to make sure to do two things: make sure to properly null terminate the final array and make sure to insert spaces between lines.
Upvotes: 0
Reputation: 5456
Initialize your array to nul char ('\0'
) instead of blanks, and use a loop to print every line as string.
Upvotes: 1