I am trying to read a file and store only the digits in the array.
My Example is file.csv
"1","2","3" "1","4","6","7" "12","15"
Please do not suggest these solutions
sizeof(arr) / sizeof(arr[0]) or *(&arr + 1) - arr
because both of these don't give the length of array containing actual values. It just gives the length of array when array was declared. I want to know the length of array during run-time when actual values are present.
The Problem Statement: Find the numOfwords in each line (present in code comments).
My code is below:
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i = 0, j = 0, k = 0; char literal, string[4][10][4]; char *filename = "file.csv"; FILE *f; f = fopen(filename, "r"); while ((literal = getc(f)) != EOF) { if (isdigit(literal)) { string[i][j][k] = literal; k++; } else { if (k > 0) { string[i][j][k] = '\0'; } k = 0; } if (literal == ',') j++; if (literal == '\n') i++, j = 0; } int numOfLines = i; int total = 0; for (int p = 0; p < numOfLines; p++) { // int numOfWords = *(&string[p] + 1) - string[p]; // Returns 10 // int numOfWords = sizeof(string[p]) / sizeof(string[p][0]); // Returns 10 // // The Problem Statement: Find the numOfwords in each line. printf("numOfWords in line %p: %d\n", numOfWords); for (long int q = 0; q < numOfWords; q++) { /* code */ total += atoi(string[p][q]); } } printf("Sum = %d", total); } Any solution better than this code is appreciated.
Output:
numOfWords in line 1: 3 numOfWords in line 2: 4 numOfWords in line 3: 2 Sum = 51
sizeofoperator yields this value at compile time unless the operand is a VLA, in which case it is evaluated at runtime. But if you want to know how many "meaningful" values an array contains, maybe you want to include a sentinel value.char literal; ... while ((literal = getc(f)) != EOF) {is an infinite loop whencharis unsigned and insufficient whencharis signed and(char)EOFis read. Useint literal;char literal, string[4][10][4];is always a 4x10x4 array ofchar. Content is irrelevant.