我的代码进一步解释。询问用户是否有帐户,如果他们这样做,则代码应该查看文件并将用户输入与文件中的内容相匹配。我读过这应该与getline一起工作,但我不理解那部分。我几乎开始使用一位不想教本书中没有的任何教师的C ++。
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string username[20];
string password[8];
string answer;
string line;
string fname, lname;
ifstream ifile("Users.text");
ifile.open("Users.txt");
ofstream ofile("Users.txt");
ofile.open("Users.txt");
cout<<"Do you have an account with us?"<<endl;
cin >> answer;
if(answer == "yes" || answer == "Yes")
{
cout<<"Please enter your username."<<endl;
cin>>username;
cout<<"Please enter your password."<<endl;
cin>>password;
while(getline(ifile, line))
{
istringstream iss(line);
if(getline(iss, username, ','))
{
//some magic is supposed to happen here.
}
}
}else if(answer == "no" || answer == "No") {
cout<<"Name: ";
cin>>fname>>lname;
}
return 0;
}
答案 0 :(得分:1)
这些行:
std::string username[20];
std::string password[8];
是个大问题。它们声明了字符串数组。既然你从不使用这种数组的任何元素,只读1个用户名/密码,似乎有人将C代码翻译成C ++¹。只需删除数组维度:
std::string username;
std::string password;
至于“魔术”,请点击评论中的链接。我们无法帮助,因为我们不知道文件中有什么。 等待*我们** 知道文件中有什么,因为
std::ofstream ofile("Users.txt");
ofile.open("Users.txt");
覆盖它。所以该文件是EMPTY。至少纠正这一点。
if (getline(iss, username, ',')) {
覆盖用户输入的用户名...也许 数组的用途是什么?无论如何,它看起来不像需要来存储文件的内容²,所以只需使用一个单独的变量:
<强> Live On Coliru 强>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string username;
std::string password;
std::string fname, lname;
std::ifstream ifile("Users.txt");
//std::ofstream ofile("Users.txt");
//ofile.open("Users.txt");
std::cout << "Do you have an account with us?" << std::endl;
std::string answer;
std::cin >> answer;
if (answer == "yes" || answer == "Yes") {
std::cout << "Please enter your username." << std::endl;
std::cin >> username;
std::cout << "Please enter your password." << std::endl;
std::cin >> password;
std::string line;
bool verified = false;
while (getline(ifile, line)) {
std::istringstream iss(line);
std::string u, pw;
if (getline(iss, u, ',') && getline(iss, pw, '\n')) {
if (u == username && pw == password) {
verified = true;
break;
}
}
}
if (verified) {
std::cout << "Welcome back, " << username << "\n";
} else {
std::cout << "Username not valid or password incorrect\n";
}
} else if (answer == "no" || answer == "No") {
std::cout << "Name: ";
std::cin >> fname >> lname;
}
}
C中的¹,一种常见的模式是使用char[]
缓冲区来存储原始字符串内容
²或者您可能需要本书未讲述的数据结构......:)