【发布时间】:2017-04-28 07:26:53
【问题描述】:
我正在尝试读取格式如下示例的文件:
3 3 1.5 50
0 2 46.0 0
* 1 46.0 1
2 * 46.0 0
0 0 50.0 0
* * 42.0 0
2 2 36.1
2 1 42 0
0 1 48.0 0
1 0 48 0
首先我想将文件的内容存储在一个字符串中。然后,我想扫描字符串并查看是否有任何星号 *.出于某种原因,我无法将其存储为字符串。每当我尝试打印字符串时,它都会给我空白行。有没有一种简单的方法可以从文件中读取数据并将其存储到字符串中?稍后我会将数值数据转换为数组。
代码sn-p:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *id; //Input Data
double *detect;
int nx, ny, i, j, k, n, count, t, frequency;
double a;
char val;
n = 0;
id = fopen(argv[1], "r");
frequency = atoi(argv[2]);
if(id){
fscanf(id, "%d %d %lf %d", &nx, &ny, &a, &tn);
}
detect = (double *) malloc(nx*nx*4*sizeof(double));
if(id){
for(i=0; i<2; i++){
fscanf(id,"%s", (detect+i));
}
}
//~ The rest of the code is left out ~
return 0;
}
【问题讨论】:
-
*无法使用%d读取。最快修复:使用%c并检查读取的值是否为*,否则将其用作数字。 -
为什么要使用
double类型来读取为字符串? -
你为什么要分配
nx * sizeof(double)字节? -
使用fgets。
-
但是使用
double *读取字符串仍然很奇怪......