that_one_nigga_you_k

lista 4 com fgets

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