2012-01-05 86 views
0

我編寫了一個基本上讀取主項目文件中保存的文本文件中的2行的程序。值得注意的是我的操作系統是Windows。我只需要閱讀第一行和第二行的特定部分。例如,我有一個文本文件,其中有兩行:用戶:管理員和密碼:stefan。在我的程序中,我要求用戶輸入用戶名和密碼,並檢查它是否與文本文件中的相匹配,但是這些行包含一些不必要的字符串:「User:」和「Password:」。有什麼方法可以閱讀所有內容,但排除不必要的字母嗎?這是我用來從文件中讀取的代碼:使用ifstream從字符串讀取數據的特定部分

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() 
{ 
    ifstream myfile("Hello.txt"); 
    string str, str2; 
    getline (myfile, str); 
    getline(myfile, str2); 
    return 0; 
} 

其中str是文本文件的第一行,str2是第二行。

+0

我認爲下面的回答將幫助你:http://stackoverflow.com/questions/1101599/good-c-string-manipulation-library – dean 2012-01-05 17:27:56

+0

我只是檢查它,但不支持我的編譯器。有一種更簡單的方法嗎?如果沒有,我只需更改我的編譯器 – Bugster 2012-01-05 17:31:04

回答

2

此代碼從名爲user.txt的文件加載用戶和密碼。

內容的文件:

user john_doe 
password disneyland 

它讀取使用getline(myfile, line)一條線,分割使用istringstream iss(line) 行並存儲在不同的字符串用戶名和密碼。

#include <iostream> 
#include <fstream> 
#include <string> 
#include <sstream> 
using namespace std; 

int main() 
{ 

    string s_userName; 
    string s_password ; 
    string line,temp; 

    ifstream myfile("c:\\user.txt"); 

    // read line from file 
    getline(myfile, line); 


    // split string and store user in s_username 
    istringstream iss(line); 
    iss >> temp; 
    iss >> s_userName; 

    // read line from file 
    getline(myfile, line); 

    // split string and store password in s_password 
    istringstream iss2(line); 
    iss2 >> temp; 
    iss2 >> s_password; 

    //display 
    cout << "User  : " << s_userName << " \n"; 
    cout << "Password : " << s_password << " \n"; 
    cout << " \n"; 

    myfile.close(); 
    return 0; 
} 
+0

輝煌。謝謝。 – Bugster 2012-01-05 19:42:44

+0

不客氣。 – 2012-01-05 19:57:24

相關問題