使用 ifstream 从字符串中读取数据的特定部分
我编写了一个程序,基本上从主项目文件中保存的文本文件中读取 2 行。值得注意的是,我的操作系统是Windows。我只需要阅读第一行和第二行文本的特定部分。例如,我有一个文本文件,其中有 2 行:用户:管理员和密码: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 是第二行。
I wrote a program that basically reads 2 lines from a text file saved in the main project file. It's notable that my OS is Windows. I need to read only specific parts of text from the first and 2nd line. For example I have one text file which has 2 lines: User: Administrator and password: stefan. Within my program I'm asking the user for the username and the password, and checks if it matches the one in the text file, however the lines contain some unnecessary strings: "User:" and "Password:". Is there any way to read everything but exclude the unnecessary letters? This is the code I'm using to read from file:
#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;
}
Where str is the first line from the text file and str2 is the 2nd.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码从名为
user.txt
的文件加载用户和密码。文件内容:
使用
getline( myfile, line )
读取一行,使用istringstream iss(line)
分割该行并将用户和密码存储在单独的字符串中。
This code loads the user and password from a file named
user.txt
.Contents of file:
It reads a line using
getline( myfile, line )
, splits the line usingistringstream iss(line)
and stores the user and password in separate strings.