2012-01-05 84 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

相关问题