2010-11-18 48 views
0

爲什麼此代碼打印字符,而沒有第一個字符?它說ocalhost而不是localhost。感謝您的幫助。第一個字符在ifstream中消失

#include <winsock2.h> 
#include <mysql/mysql.h> 
#include <iostream> 
#include <windows.h> 
#include <fstream> 
using namespace std; 

int main() {  
int b = 0; 
char * pch; 
int stringLength = 0; 
char textRead[50]; 
ifstream infile("config.ini", ios::in | ios::binary);    
if(!infile) { 
      cout << "ERROR: config.ini not found!\n"; 
      system("pause"); 
      exit(0); 
} 

infile >> textRead; 
stringLength = strlen(textRead); 
pch=strchr(textRead,'"'); 
while(pch != NULL) { 
      infile.seekg(pch-textRead-1); 
      infile >> textRead; 
      pch = strchr(pch+1,'"'); 
} 
cout << textRead; 
infile.close(); 
+0

無法分辨'config.ini'的內容。 – 2010-11-18 19:11:27

+2

你爲什麼要編寫解析INI文件的代碼呢?您明確使用Windows,因此請調用['GetPrivateProfileString'](http://msdn.microsoft.com/zh-cn/library/ms724353.aspx)以獲取所需的INI值。 – 2010-11-18 21:00:07

回答

0

內部while循環您撥打:

infile >> textRead; 
    pch = strchr(pch+1,'"'); 

當您嘗試在第二行中運行strchr,它仍然再參照以前的字符串你在textRead不是最近提取出的詞有。

不幸的是我不能推斷出你實際上正在做什麼,所以我不能提供關於如何解決它的建議。

0

我猜config.ini的內容,因爲你沒有提供它,但它看起來像ifstream閱讀就好了。在您的infile >> textRead;後面加上cout << textRead << endl;進行檢查。這是我使用的是什麼config.ini

localhost = "foo" 

您與seekg和朋友邏輯似乎打破,雖然。 seekg不是用來支持解析(在你的情況下,跳過引號);它意味着在需要時跳過大塊文件,所以你不會浪費時間閱讀文件。老實說,我不確定你在做什麼,因爲如果第一個字符是引用,pch-textRead-1可能是-1。

另一件事是infile >> textRead;不讀取一行,它讀取一個單詞,並丟棄領先的空白。

爲了記錄在案,我省略

#include <winsock2.h> 
#include <mysql/mysql.h> 
#include <windows.h> 

因爲不需要它。