fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define BUF_32 32
  6.  
  7. void removeEOL(char *s){
  8. char *newline = strchr( s, '\n' );
  9. if ( newline )
  10. *newline = 0;
  11. }
  12.  
  13. char *strtok_r(char *str, const char *delims, char **store);//strtok_r is not included in c99
  14.  
  15. void tokenizer2D(char *s, const char *delimiter, int ncols, int maxStrSize, char rowVec[ncols][maxStrSize]){
  16. char *saveptr;
  17. char *token = strtok_r(s, delimiter, &saveptr);
  18. int j = 0;
  19.  
  20. while (token && j < ncols){
  21. strcpy(rowVec[j++], token);
  22. token = strtok_r(NULL, delimiter, &saveptr);
  23. }
  24. }
  25.  
  26. void read2mat(const char delim[], int nrows, int ncols, int maxStrSize, char mat[nrows][ncols][maxStrSize]){
  27. char linea[maxStrSize];
  28. int i = 0;
  29.  
  30. while (fgets(linea, maxStrSize, stdin) && i < nrows){
  31. removeEOL(linea);
  32. tokenizer2D(linea, delim, ncols, maxStrSize, mat[i++]);
  33. }
  34. }
  35.  
  36. int main(void){
  37. int N = 3, M = 5;
  38. char (*A)[M][BUF_32] = malloc(sizeof(char[N][M][BUF_32]));
  39.  
  40. read2mat(", ", N, M, BUF_32, A);
  41. for(int r = 0; r < N; ++r){
  42. for(int c = 0; c < M; ++c){
  43. printf("%s ", A[r][c]);
  44. }
  45. puts("");
  46. }
  47. free(A);
  48. return 0;
  49. }
  50. //Because strtok_r is not included in c99
  51. char *strtok_r(char *str, const char *delims, char **store){
  52. char *p, *wk;
  53. if(str != NULL){
  54. *store = str;
  55. }
  56. if(*store == NULL) return NULL;
  57. *store += strspn(*store, delims);//skip delimiter
  58. if(**store == '\0') return NULL;
  59. p=strpbrk(wk=*store, delims);
  60. if(p != NULL){
  61. *p='\0';
  62. *store = p + 1;
  63. } else {
  64. *store = NULL;
  65. }
  66. return wk;
  67. }
  68.  
Success #stdin #stdout 0s 2248KB
stdin
one, two, three, four, five
red, blue, green, white, black
apple,cherry,orange,lemon,peach
stdout
one two three four five 
red blue green white black 
apple cherry orange lemon peach