rrz0

Splitting string

Dec 12th, 2018
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main(void) {
  5.     //char line[] = "Foo Bar 42";
  6.         char line[20];
  7.         char name[20][20];
  8.         char name_r[10];
  9.         char surname_r[10];
  10.         FILE *inp; /* pointer to input file */
  11.        
  12.         inp = fopen("in_file.txt", "r");
  13.     {
  14.         if (inp) {
  15.             while (fgets(line, sizeof line, inp)) {    
  16.                
  17.                 int age;
  18.                 char *space = strrchr(line, ' ');
  19.                 if (!space) /* error, bad line */;
  20.                 if (space - line >= 30) /* error, name too long */;
  21.                 sprintf(name, "%.*s", space - line, line);
  22.                 age = strtol(space, NULL, 10); // needs error checking
  23.                 printf("[%s]; %d\n", name, age);
  24.         // ...}
  25.             }
  26.         }
  27.        
  28.        
  29.        }
  30.     return 0;
  31. }
  32.  
  33. Input:
  34. Patrice Evra 95
  35. Rio Ferdi 96
  36. Marcus Rash 78
  37. Wayne Roon 69
  38. Alex Ferg 100
  39. Nemanja Vida 78
  40.  
  41.  
  42. Output:
  43. [Patrice Evra]; 95
  44. [Rio Ferdi]; 96
  45. [Marcus Rash]; 78
  46. [Wayne Roon]; 69
  47. [Alex Ferg]; 100
  48. [Nemanja Vida]; 78
Advertisement
Add Comment
Please, Sign In to add comment