2012-09-02 42 views
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 

等。我只關注文件中的前兩個數字,即10和1.

+1

變量'N'是什麼? – hmjd

+0

你是如何申報N的? – piokuc

+0

順便說一句,你應該使用'%p'打印'f',而不是'%d'。 – hmjd

回答

0

正如我在my comment中所述,問題在於您的格式說明符不正確。嘗試

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

由於您使用cout我fathoming猜測,這其實是C++代碼...說實話,你真的應該做這個規範Ç方式。相反,使用ifstream

std::ifstream input("network.dat"); 
int N, read; 
input >> N >> read; 
std::cout << N << ' ' << read << std::endl; 
+0

這是一個錯字,我糾正了它。感謝您指出。 – Srijan

+0

@Srijan你能告訴我們什麼是「錯誤」嗎?你有什麼問題?你可以發佈[SSCCE](http://sscce.org)嗎? – oldrinb

+0

@Srijan我*高*建議您使用C++的替代品。 – oldrinb

0

您的代碼需要文件中的所有字符,直到第一個空格爲int。如果文件不是以int開頭的,那可能是它失敗的原因。

1

您的scanf()格式字符串不正確。 「%d,%d」查找用逗號分隔的兩個整數。如果你想讀取兩個用空格分隔的整數,只需執行「%d%d」即可。

+0

這是一個錯字,我已經糾正它。感謝您指出。 – Srijan

+0

如果您發現scanf()函數沒有提供您期望的內容,請首先檢查格式字符串是否正確,然後檢查您是否傳遞了指針(您在此處)。 – teppic

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"; 
     } 
}