如何从c中的文本文件中逐列阅读。 [英] How to read column wise from text file in c.

查看:83
本文介绍了如何从c中的文本文件中逐列阅读。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中以2D矩阵的形式输入。

对于我的问题,我打算执行以下操作:

1.来自文本文件,我需要读取每一行并将每行的元素存储在一个临时的一维数组中。

2.我需要计算每行对应的某些参数。

3.我对每一栏都做了同样的事情。但是我无法将列值存储在类似的一维数组中。

4.出现的问题是它只是行读取元素而只存储行元素。



我如何纠正这个问题。

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.






我尝试过:



printf(ROWS \ n);

f2 = fopen(Cost.txt,r);

for(i = 0; i< m; i ++)>

{

for(k = 0; k< n; k ++)>

{

fscanf(f2,%d,& r [k]) ;

printf(r [%d] =%d \ t,k,r [k]);

// r [k] = c [我] [k];

}

}



同样我也试过列但是它不起作用。

注意:我想知道如何按列存储值。



What I have tried:

printf("ROWS\n");
f2=fopen("Cost.txt" , "r");
for(i=0;i<m;i++)>
{
for(k=0;k<n;k++)>
{
fscanf(f2,"%d", &r[k]);
printf("r[%d]=%d\t",k,r[k]);
//r[k]=c[i][k];
}
}

Similarly i tried for columns also but its not working.
NOTE : I want to know how to store values column wise.

推荐答案

使用 fgets - C ++参考 [ ^ ]将文本文件逐行读入缓冲区。然后解析每一行以获取列元素。这取决于文本文件的格式。解析函数候选者是 sscanf - C ++ Reference [ ^ ]和 strpbrk - C ++参考 [ ^ ]或解析分隔符并使用 atoi() atof()获取数值。



基本实现:

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);
        // ...
        row++;
    }
    fclose(f2);
}


这篇关于如何从c中的文本文件中逐列阅读。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆