Click here to Skip to main content
15,794,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have my input in the form of a 2D matrix in a text file.
For my problem i have intend to do the following:
1. From the text file, i need to read each row and store the elements of each row in a temporary one dimensional array.
2. I need to compute certain parameters corresponding to each row.
3. I got to similarly do for each column. But i am unable to store the column values in a similar one dimensional array.
4. The problem arising is that it is reading elements row wise only and storing the row elements only.

How do i rectify this problem.

What I have tried:

f2=fopen("Cost.txt" , "r");
fscanf(f2,"%d", &r[k]);

Similarly i tried for columns also but its not working.
NOTE : I want to know how to store values column wise.
Updated 9-Feb-16 1:00am

1 solution

Use fgets - C++ Reference[^] to read the text file line by line into the buffer. Then parse each line to get the column elements. This depends on the format of your text files. Parsing function candidates are sscanf - C++ Reference[^] and strpbrk - C++ Reference[^] or parsing for delimiters and using atoi() and atof() for numeric values.

A basic implementation:
int elements[MAX_ROWS][MAX_COLUMNS];
FILE f2 = fopen("Cost.txt" , "r");
if (NULL != f2)
    int row = 0;
    char lineBuf[MAX_LINE_LENGTH];
    while (NULL != fgets(buf, sizeof(lineBuf), f2))
        int col = 0;
        // Get column elements from lineBuf here into elements[row][col]
        //  locating the next column parsing for delimiters.
        // This depends on the file format
        const char *colData = lineBuf;
        elements[row][col++] = atoi(colData);
        // ...
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900