练习: 使用Obj C和C,创建一个命令行应用程序,它将: •以下列格式获取带有笛卡尔坐标的txt文件:
(2;9)
(5;6)
...
•(其他技术要求)
问题:处理输入数据的最佳方法是什么?
C具有fscanf
fgetc
和fgets
等功能。
如果我理解正确 - 我们不能使用fgets
- 因为它适用于不是整数/浮点数/双打的字符。它会读取每个角色。
我们不能使用fgetc
- 因为它只返回转换为int的1个字符(流中的下一个字符)。
我有几种方法,但到目前为止还没有。
首先 - 使用for
循环。我想先计算坐标对的数量,然后将.txt文件中的数据整理成2个数组,用于x和y坐标:
float xCoordinate [MAXSIZE] = {0.0};
float yCoordinate [MAXSIZE] = {0.0};
float x;
float y;
FILE *handle;
handle = fopen ("points.txt", "r");
int ch;
int n;
ch=fgetc(handle)!=EOF; //error. This will read every character including ( ) and ; .
//Maybe I omit this loop condition?
for (n=0; n<=ch ; (fscanf(handle, "(%f;%f)", &x, &y) )
{
xCoordinate [n+1] = x;
yCoordinate [n+1] = y;
}
答案 0 :(得分:1)
只要fscanf返回两个成功读取的项目并且n小于MAXSIZE,就应该读取该文件。
float xCoordinate [MAXSIZE] = {0.0};
float yCoordinate [MAXSIZE] = {0.0};
float x;
float y;
FILE *handle;
int n = 0;
if ( ( handle = fopen ("points.txt", "r")) == NULL)
{
printf ("could not open file\n");
return 1; // or exit(1);
}
while ( ( fscanf(handle, " (%f;%f)", &x, &y) ) == 2)
{
xCoordinate[n] = x;
yCoordinate[n] = y;
n++;
if ( n >= MAXSIZE)
{
break;
}
}
fclose ( handle);
答案 1 :(得分:0)
Someone answered this question and then deleted it. Luckily, I saved his code. The best part - it works:
float xCoordinate [MAXSIZE] = {0.0};
float yCoordinate [MAXSIZE] = {0.0};
float x;
float y;
FILE *handle;
int n = 0;
if ( ( handle = fopen ("points.txt", "r")) == NULL)
{
printf ("could not open file\n");
return 1; // or exit(1);
}
while ( ( fscanf(handle, " (%f;%f)", &x, &y) ) == 2)
{
xCoordinate[n] = x;
yCoordinate[n] = y;
n++;
if ( n >= MAXSIZE)
{
break;
}
}
fclose ( handle);