0

我编写了一个从名为 network.dat 的文件中读取的代码

我写的代码是

    f = fopen("network.dat", "r");
    if(f == NULL)
        exit(1);
    int read, N;

    printf("%p\n", f);//output file pointer, included this just to check if file is opened properly
    fscanf(f, "%d%d", &N, &read);//error here
    cout<<N; 

该文件正在正确打开并且正在获取文件指针(49897488)作为输出,但它后面的行是程序停止工作的地方,我没有得到N作为输出。请告知是否需要其他详细信息。network.dat 的内容是

10 1
1   6   1.28646
1   7   1.2585
2   9   1.33856

等等。我只关注文件中的前 2 个数字,即 10 和 1。

4

4 回答 4

1

您的 scanf() 格式字符串不正确。"%d,%d" 查找用逗号分隔的两个整数。如果要读取两个用空格分隔的整数,只需执行“%d%d”即可。

于 2012-09-02T19:56:55.337 回答
1

这似乎对斯里扬有效。该代码是一种快速而肮脏的剪切和粘贴工作,风格零分,但它作为测试完成了这项工作。似乎记录中的字段数需要与打印格式字符串中的字段匹配。我在 1.9999 的记录 1 的测试数据中添加了第三个字段,它起作用了。我怀疑这是一个技术上纯粹的解释。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
using std::ios;

int main(int argc, char *argv[])
{
//int read;
//int N;
int res;
FILE *f;


f = fopen("network.dat", "r");
    if(f == NULL)
        exit(1);
    int read, N;
    float f3;

    printf("%p\n", f);//output file pointer, included this just to check if file is opened properly
    for (;;)
        {
    res = fscanf(f, "%d%d%f", &N, &read, &f3);//error here
    if (res <= 0)
        {
        printf("err %d\n",errno);
        break;
        }
    cout<<N << " " << read << "\n";
        }
}
于 2012-09-03T02:40:10.430 回答
0

您的代码期望文件中的所有字符直到第一个空格都是 int。如果文件不是以 int 开头,这可能是它失败的原因。

于 2012-09-02T19:47:24.750 回答
0

正如我在评论中所说,问题在于您的格式说明符不正确。尝试

fscanf(f, "%d%d", &N, &read);

由于您使用cout的是我猜测这实际上是 C++ 代码......老实说,您真的应该以规范的 C 方式来做这件事。相反,使用ifstream.

std::ifstream input("network.dat");
int N, read;
input >> N >> read;
std::cout << N << ' ' << read << std::endl;
于 2012-09-02T19:59:43.550 回答