gpt4 book ai didi

c++ - 使用 ifstream 从字符串中读取数据的特定部分

转载 作者:行者123 更新时间:2023-11-28 03:42:19 27 4
gpt4 key购买 nike

我编写了一个程序,基本上从保存在主项目文件中的文本文件中读取 2 行。值得注意的是,我的操作系统是 Windows。我只需要阅读第一行和第二行的特定部分文本。例如,我有一个包含两行的文本文件:用户:Administrator 和密码:stefan。在我的程序中,我要求用户输入用户名和密码,并检查它是否与文本文件中的匹配,但是这些行包含一些不必要的字符串:“用户:”和“密码:”。有没有办法阅读所有内容但排除不必要的字母?这是我用来从文件中读取的代码:

#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 是第二行。

最佳答案

此代码从名为 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;
}

关于c++ - 使用 ifstream 从字符串中读取数据的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8746656/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com