c - 文本文件中矩阵的维度
问题描述
我想以形式评估方阵的维度
-2 2 -3
-1 1 3
2 0 -1
所以在这种情况下n = 3,我的代码可以读取所有整数的数量,但我想停在第一行并获取前3个数字..
#include <stdio.h>
int main(){
int temp;
int n = 0;
FILE *file = fopen("matrix","r");
if(file == NULL){
printf("Could not open specified file");
return 1;
}
while(fscanf(file,"%d",&temp) == 1){
n++;
}
fclose(file);
printf("%d",n);
return 0;
}
解决方案
我可能有一些过于复杂的事情,但如果我必须这样做,我会这样做。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* file_in = fopen("mat1", "r");
char c;
int temp;
int n = 0;
if (file_in)
{
// you get the characters one by one and check if
// if it is an end of line character or EOF
while ((c = (char)fgetc(file_in)) != '\n' && c != EOF)
{
// if it wasn't, you put it back to the stream
ungetc(c, file_in);
// scan your number
fscanf(file_in, "%d", &temp);
n++;
}
fclose(file_in);
}
else
{
fprintf(stderr, "Could not open specified file.\n");
return 1;
}
printf("Number of numbers: %d\n", n);
return 0;
}
也许这回答了你的问题......但是我认为它会更简单,(如上所述)看fgets
. 之后你甚至不需要sscanf
读取行,因为如果你的矩阵实际上是一个方阵,那么你得到的行数就是你的矩阵的维数。干杯!
推荐阅读
- php - 使用 ENDPOINT 未捕获的 axios 在本机反应中发布/传递数据数组
- java - 如何对数组列表的元素求和?
- mocking - mockcpp:为什么 any() 不模拟后两个参数?
- saml - 为什么在 OneLogin 中创建具有自定义属性的用户会返回 422 ""invalid user custom attribute(s) _____ and ___"?
- kubernetes - 如何避免 Rancher RKE Reconcile 警告?
- javascript - Firebase 侦听器管理模式
- css - Avada Live Builder 显示与实际站点不匹配
- batch-file - 使用批处理文件复制文件名并附加另一个文件
- c - 如何从 .h 文件返回主 c 文件?
- applescript - AppleScript 发送 WhatsApp