I am writing a C code that reads numbers from a file and I am stuck on how to write the following in C, I know the C++ equivalent which is what I have here:
ifstream inFile;
inFile >> rows;
inFile >> matrix[i][j];
sumOfRows[i] += matrix[i][j];
Copyright © 2024 QUIZLS.COM - All rights reserved.
Answers & Comments
Here's a simple example:
/*
. * Read the specified input text file that contains the dimensions
. * and contents of a matrix of integers. The first line is:
. * rows columns
. * Subsequent rows contain the matrix data.
. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 1024
#define WHITESPACE " ,\t"
FILE *openFile(const char *prompt, const char *mode);
int main(int argc, char *argv[]) {
. . char numstr[MAX_STR_LEN],*s;
. . int n, rows, cols, i, j, **matrix;
. . FILE *in;
. . if ((in = openFile("Enter input file name: ","r")) != NULL) {
. . . . s = fgets(numstr,MAX_STR_LEN,in);
. . . . if ((sscanf(s,"%d %d",&rows, &cols) == 2) && (rows > 0) && (cols > 0)) {
. . . . . . matrix = calloc(rows, sizeof(int *));
. . . . . . for (i = 0; i < rows; i++) {
. . . . . . . . matrix[i] = calloc(cols, sizeof(int));
. . . . . . . . s = fgets(numstr, MAX_STR_LEN, in);
. . . . . . . . *(strchr(numstr,'\n')) = '\0';
. . . . . . . . if (strlen(s) > 0) {
. . . . . . . . . . j = 0;
. . . . . . . . . . while ((s != (char *)NULL) && (j < cols)) {
. . . . . . . . . . . . if (sscanf(s,"%d",&n) == 1) {
. . . . . . . . . . . . . . matrix[i][j++] = n;
. . . . . . . . . . . . }
. . . . . . . . . . . . if ((s = strpbrk(s, WHITESPACE)) != (char *)NULL) {
. . . . . . . . . . . . . . s = &s[strspn(s, WHITESPACE)];
. . . . . . . . . . . . }
. . . . . . . . . . } /* end for each column in row i */
. . . . . . . . } /* end if not empty line */
. . . . . . } /* end for each row */
. . . . . . for (i = 0; i < rows; i++) {
. . . . . . . . for (j = 0; j < cols; j++) {
. . . . . . . . . . printf("%d ", matrix[i][j]);
. . . . . . . . }
. . . . . . . . puts("");
. . . . . . }
. . . . } else {
. . . . . . puts("first line in file must be: rows cols");
. . . . }
. . } else {
. . . . puts("input file not found");
. . }
. . fclose(in);
. . return 0;
}
FILE *openFile(const char *prompt, const char *mode) {
. . FILE *fp = NULL;
. . char fileName[MAX_STR_LEN];
. . printf("%s",prompt);
. . fgets(fileName,MAX_STR_LEN,stdin);
. . *(strchr(fileName,'\n')) = '\0';
. . if ((fp = fopen(fileName,mode)) == NULL) {
. . . . printf("\nerror opening %s\n",fileName);
. . }
. . return fp;
}
#if 0
Sample run:
Enter input file name: matrixData.txt
10 20 30 40
50 60 70 80
Where:
$ cat matrixData.txt
2 4
10 20 30 40
50 60 70 80
#endif
C is just C++ without the built-in stuff for objects. You can still do objects in C, but it's a lot uglier.
Will you provide code that compiles?
How to convert C++ Code to C - Stack Overflow
https://stackoverflow.com/questions/737257/how-to-...