I need to match a string matrix to another matrix, how do I do?

Asked

Viewed 131 times

1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 3
#define LEN 80
char texto[MAX][LEN];
int main(){
    char string[MAX][LEN];
    int i, j, k;
    for(i=0;i<MAX;i++){
        printf("Inf. uma string: ");
        gets(texto[i]);
    }
    printf("\n\nstrings digitadas foram\n\n");
    for(i=0;i<3;i++){
        printf("%s \n",texto[i]);
    }
    printf("\n\n");

    for(i=0;i<3;i++){
        for(k=0;texto[i][k];k++){
            if(i==2){
                string[i][k]=texto[i][k];
                printf("String 2: %s\n",string[i][k]);
            }
        }
    }
    system("pause");
    return 0;
}

1 answer

1


You can use the function strcpy() of the standard library string.h to copy each of the strings contained between the arrays two-dimensional texto[][] and string[][].

Never use the function gets()! She was considered deprecated due to the risk of buffer overflow that it represents. Use scanf() or fgets() of the standard library stdio.h.

Follow a code tested with appropriate corrections:

#include <stdio.h>
#include <string.h>

#define MAX 3
#define LEN 80

char texto[MAX][LEN];

int main(){
    char string[MAX][LEN];
    int i;

    for( i = 0; i < MAX; i++ ){
        printf("Informe string %d: ", i );
        scanf( "%s", texto[i] );
    }

    printf("\nStrings digitadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, texto[i] );

    for( i = 0; i < MAX; i++ )
        strcpy( string[i], texto[i] );

    printf("\nStrings copiadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, string[i] );

    return 0;
}

However, if the challenge is not to use the function strcpy(), Voce can try something like:

#include <stdio.h>

#define MAX 3
#define LEN 80

char texto[MAX][LEN];

int main(){
    char string[MAX][LEN];
    int i, j;

    for( i = 0; i < MAX; i++ ){
        printf("Informe string %d: ", i );
        scanf( "%s", texto[i] );
    }

    printf("\nStrings digitadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, texto[i] );

    for( i = 0; i < MAX; i++ )
        for( j = 0; j < LEN; j++ )
            string[i][j] = texto[i][j];

    printf("\nStrings copiadas foram:\n");

    for( i = 0; i < MAX; i++ )
        printf("[%d] %s \n", i, string[i] );

    return 0;
}

Exit:

Informe string 0: aeiou
Informe string 1: abcdefghijklmnopqrstuvwxyz
Informe string 2: 1234567890

Strings digitadas foram:
[0] aeiou 
[1] abcdefghijklmnopqrstuvwxyz 
[2] 1234567890 

Strings copiadas foram:
[0] aeiou 
[1] abcdefghijklmnopqrstuvwxyz 
[2] 1234567890 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.