that_one_nigga_you_k

lista 4 com fgets e função de ler

Dec 15th, 2023
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. void ler(char*** str, int* indice) {
  6.     int flag = 1;
  7.  
  8.     while (flag) {
  9.         (*str)[*indice] = (char*)malloc(1000 * sizeof(char));
  10.  
  11.         if ((*str)[*indice] == NULL) {
  12.             printf("deu errado essa porra ae");
  13.             flag = 0;
  14.         }
  15.  
  16.         printf("digite a string: \n");
  17.  
  18.         if (fgets((*str)[*indice], 1000, stdin) != NULL) {
  19.             if ((*str)[*indice][0] == '\n') {
  20.                 flag = 0;
  21.             }
  22.            
  23.             else {
  24.                 (*str)[*indice][strcspn((*str)[*indice], "\n")] = '\0';
  25.                 (*indice)++;
  26.                 *str = realloc(*str, (*indice + 1) * sizeof(char*));
  27.  
  28.                 if (*str == NULL) {
  29.                     printf("\n deu ruim isso aí ein\n");
  30.                     flag = 0;
  31.                 }
  32.             }
  33.         }
  34.        
  35.         else {
  36.             flag = 0;
  37.         }
  38.     }
  39. }
  40.  
  41.  
  42.  
  43. int main(){
  44.     char** str = NULL;
  45.  
  46.     str = (char**)malloc(1 * sizeof(char*)); //malocando a quantidade de strings
  47.  
  48.     if(str == NULL){
  49.         printf("\ndeu mto ruim saporra\n");
  50.     }
  51.  
  52.     int indice = 0;
  53.  
  54.     ler(&str, &indice);
  55.    
  56.     printf("\naí as strings\n\n");
  57.  
  58.     for(int i = 0 ; i < indice ; i++){
  59.         printf("\n%s", str[i]);
  60.         free(str[i]);
  61.     }
  62.  
  63.     free(str);
  64.  
  65.     printf("\n\naté mais...\n\n");
  66.  
  67.     return 0;
  68. }
Add Comment
Please, Sign In to add comment