好吧所以我用C而不是C ++制作生活游戏,因为我们不允许使用字符串库,我只是想知道如何计算任意输入文件的行和列..
是的,这是一个家庭作业,但这只是一个开始..而且我被困住,觉得自己像个白痴。
以下是一个例子:
00000000100000001010
00000000010000001001
11100000010100000010
10100100101010101010
00101010010010101000
所以我需要一种简单的方法来计算任意文件中的行和列,我猜你会用char来计算char的列数和逐行的行数,但是每次我尝试这样的东西时它都会混乱。< / p>
所以请帮帮我,谢谢!
答案 0 :(得分:1)
你需要在c右边做。 ok首先使用somemethod计算每行中的字符数。让len1为行长。然后使用
fseek(fp, 0, SEEK_END);
len2 = ftell(fp);
然后len2 = len2 /(len1 + 1)。将1添加到len1以考虑每行末尾的换行符和最后一行的EOF。那么矩阵大小是(len1,len2)
答案 1 :(得分:0)
这样的事情应该有效
char *matrix; // this is our matrix read in from file
int rows = 0;
int cols = 0;
int tempCols = 0;
int index = 0;
// assumes matrix is a null-terminated string
while (matrix[index] != 0) {
tempCols++;
if (matrix[index] == '\n') {
rows++;
if (tempCols > cols) {
// this will return the largest column size if it's not rectangular
cols = tempCols;
tempCols = 0;
}
答案 2 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
FILE *fp;
int row = 0, col = 0;
char c;
fp = fopen("file","r+");
while( (c = fgetc(fp)) != EOF ){
if(c != '\n' && row == 0){
col++;
}
else if(c == '\n')
row++;
}
row++; /* If your file doesn't end with a \n */
printf("Rows = %d\tColumns = %d\n",row,col);
return 0;
}
此处“file”是您任意输入文件的名称 注意:只有当文件末尾没有“输入”时,此代码才能正常工作。