2012-02-24 71 views
0

你能帮我解决这个问题吗?我试图完成的是当用户输入他/她的用户名和密码时,我的程序将打开一个文件是按行(用户名,密码,文件夹名,用户全名)排列的用户信息存储。我有这个代码,但我似乎无法看到问题。当输入应该有第一行的结果时,它就会得到它。但是当它解析第二行时,它会崩溃。有人可以帮我弄这个吗?读取文件并标记数据以与C++中的输入进行比较

#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

可能是你满溢ONELINE缓冲区。 而不是使用固定的大小,只需使用std :: string,就像您为其他变量所做的那样。 即

string oneline; 
... 
oneline = line; 
... 

并使用boost tokenizer对逗号分割,代替的strtok

编辑:样品使用,改编自升压文档

#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 
+0

我已经尝试使用字符串作为数据键入但无济于事。关于boost标记器,它是否可以在Firebreath中使用? – 2012-02-25 07:07:24

+0

不容易:仅包含标题,请参阅编辑答案 – CapelliC 2012-02-25 13:21:13

相关问题