# Thread: How to store a string letter by letter in a 2D matrix?

1. ## How to store a string letter by letter in a 2D matrix?

It takes a string and key both chars. The amount of columns are determined by the length of the key. However, I'm not getting this to work.

Code:
```#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <math.h>

int main(){
char key[50];
char line[256];

if (fgets(line, sizeof line, stdin) == NULL) {
exit(EXIT_FAILURE);
}

if (fgets(key, sizeof key, stdin) == NULL) {
exit(EXIT_FAILURE);
}

int len = strlen(line);
if (len && line[len - 1] == '\n')
line[--len] = '\0';

int len1 = strlen(key);
if (len1 && key[len1 - 1] == '\n')
key[--len]= '\0';

printf("%s\n", line);
printf("%s\n", key);

gridStr(line,key);
}

void gridStr(char *line, char *key)
{
int mat[10][10];    int j=0;
int i;
int ctr=j;
printf("The matrix is:\n");
for(i=0;i<strlen(line);i++)
{
for(j=j;ctr<strlen(key);j++)
{
if(line[j]!='\0')
{
mat[i][ctr]=line[j];
printf("%c",mat[i][j]);
ctr++;
}
else
{

}
}
}
}```

2. You had working code here.
Code:
```void gridStr(char *line, char *key)
{
int columns = strlen(key)-1;
int i = 0;
while (line[i]) {
putchar(line[i++]);
if (i % columns == 0) putchar('\n');
}
if (i % columns != 0) putchar('\n');
}```
What you lacked was a counter for rows.
Code:
```void gridStr(char *line, char *key)
{
char mat[10][10];
int columns = strlen(key)-1;
int rows = 0;
int i = 0;
while (line[i]) {
mat[rows][columns] = line[i++];  // store instead of print
if (i % columns == 0) rows++
}
if (i % columns != 0) rows++;
}```

3. ## Thanks!

But I'm not getting it to print using putchar() so can I use a for loop and print the matrix instead?

4. Of course it doesn't print anything.
It's purpose is to compute the grid.

Here's something for you to study.
Code:
```#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void trimNewline(char *line) {
size_t len = strlen(line);
if (len && line[len - 1] == '\n')
line[len - 1] = '\0';
}

void inputLine(char *line, size_t max, const char *prompt) {
printf("%s", prompt);
if (fgets(line, max, stdin) == NULL) {
exit(EXIT_FAILURE);
}
trimNewline(line);
}

void gridStr(char mat[10][10], size_t columns, const char *line)
{
size_t r = 0, c = 0;
int i = 0;
while (line[i]) {
mat[r][c] = line[i++];
if ( ++c == columns ) {
c = 0;
r++;
}
}
}

void printGrid(const char mat[10][10], size_t rows, size_t columns) {
for ( size_t r = 0 ; r < rows ; r++ ) {
for ( size_t c = 0 ; c < columns ; c++ ) {
putchar(mat[r][c]);
}
putchar('\n');
}
}

int main(){
char str[50];
char key[50];

size_t columns = strlen(key);
size_t rows = (strlen(str) + columns - 1) / columns;
char mat[10][10] = { { 0 } };

gridStr(mat, columns, str);
printGrid(mat, rows, columns);

return 0;
}

\$ gcc foo.c
\$ ./a.out
thi
slo
ngl
ine
.
\$```
First, anytime you start copy/pasting more than a few lines of code, you should be making a function out of it.