你可以帮我解决这个问题吗...我想要完成的是当用户输入他/她的用户名和密码时,我的程序将打开一个文件,该文件是按行排列的用户信息的存储(用户名,密码,foldername,用户的全名)。我有这个代码,但我似乎无法看到问题。当输入应该具有第一行的结果时,它就会得到它。但当它解析第二行时,它会崩溃。有人可以帮我这个吗?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main () {
// string toks[];
char oneline[80],*del;
string line, creds[3], username, password;
int x = 0;
cout<<"Enter Username: ";
cin>>username;
cout<<"Enter Password: ";
cin>>password;
ifstream myfile;
myfile.open("jake.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
getline(myfile,line);
strcpy(oneline,line.c_str());
del = strtok(oneline,",");
while(del!=NULL)
{
creds[x] = del;
del = strtok(NULL,",");
++x;
}
if((creds[0]==username)&&(creds[1]==password))
{
cout<<creds[2]<<endl;
break;
}
}
myfile.close();
}
else
cout << "Unable to open file";
system("pause");
}
答案 0 :(得分:0)
可能你正在溢出 oneline 缓冲区。 而不是使用固定大小,只需使用std :: string,就像你正在为其他变量做的那样。 即。
string oneline;
...
oneline = line;
...
并使用boost tokenizer对逗号进行拆分,而不是使用strtok
修改:示例用法,改编自boost docs
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int tokenizer_main(int, char **){
using namespace std;
using namespace boost;
string s = "This,is,a,test";
tokenizer<> tok(s);
for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
cout << *beg << "\n";
}
}
输出
This
is
a
test