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

  1. #1
    Registered User
    Join Date
    May 2022
    Posts
    18

    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];
     
         printf("Enter your string:");
        if (fgets(line, sizeof line, stdin) == NULL) {
            fprintf(stderr, "No line read\n");
            exit(EXIT_FAILURE);
        }
        
        printf("Enter your key");
        if (fgets(key, sizeof key, stdin) == NULL) {
            fprintf(stderr, "No line read\n");
            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. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,334
    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++;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2022
    Posts
    18

    Thanks!

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

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,334
    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) {
            fprintf(stderr, "No line read\n");
            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];
    
        inputLine(str, sizeof(str), "Please enter string:");
        inputLine(key, sizeof(key), "Please enter key:");
    
        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 
    Please enter string:thislongline.
    Please enter key:key
    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.


    A note about line 50.
    If the length of the line was a simple multiple of the length of the key, then a simple
    rows = strlen(str) / columns would suffice.

    But integer division rounds down, so if there are any excess characters to complete the last partial row, we need an extra row.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help displaying string letter by letter
    By Robsta107 in forum C Programming
    Replies: 3
    Last Post: 03-01-2017, 04:13 PM
  2. Replies: 12
    Last Post: 11-24-2012, 04:10 AM
  3. Change one letter from a string
    By gunitinug in forum C Programming
    Replies: 4
    Last Post: 12-01-2011, 04:05 AM
  4. Remove a letter from a string
    By StarOrbs in forum C++ Programming
    Replies: 6
    Last Post: 04-05-2005, 03:03 PM
  5. Big Letter became small letter
    By cogeek in forum C Programming
    Replies: 27
    Last Post: 12-13-2004, 02:04 PM

Tags for this Thread