读取文件并标记数据以与C++中的输入进行比较
read file and tokenize data to compare to input in 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");
}
您可能溢出了oneline缓冲区。不要使用固定大小,只需使用std::string,就像您对其他变量所做的那样。即
string oneline;
...
oneline = line;
...
并使用boost标记器在逗号上进行拆分,而不是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
相关文章:
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 使用-L和-L标志与将库文件作为输入进行比较
- 通过与输入进行比较来安排输出
- 将私有对象变量与用户输入的变量进行比较
- 输入迭代器的相等性比较
- 将用户输入的术语与 txt 文件中的列表进行比较
- 将 ProcessEntry32.szExeFile 与用户输入的数据进行比较时,C++ _wcsicmp代码未编译
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 从类中查看 rand() 并将用户输入与计算机选择进行比较.石头,纸,剪刀游戏
- (C++) 学习向量 - 编码/输入流终止/比较向量的问题
- 在比较特定输入中的程序的数组中出错
- 将最大最小值的数据与可变数量的输入进行比较 C++
- c++ 输入一个数字来确定其他数字,然后比较它们
- 比较输入的C弦与文件读取c-string
- 将用户输入与矢量中存储的值进行比较
- C++ - 读取和比较用户输入
- 将结果与用户输入-SQLITE3 C 进行比较
- 正在检查用户的有效输入并与文本文件进行比较
- C++如何将用户输入与具有严格排序的字符串列表进行比较