C++从文件中读取并标记数据
C++ read from file and tokenize data
我正在尝试创建一个C++程序,该程序允许我从文件中读取并从每一行中找到匹配的输入。请注意,每一行都是由昏迷分隔的单个记录。如果找到了匹配项,则预期输出将是记录中的字符串。
例如:文件中的数据=>
安德鲁,安迪,安德鲁安德森
翡翠,翡翠索尼娅刀锋输入=>翡翠
输出=>疲惫的
我该怎么做?我正在尝试实现strtok,但没有成功。到目前为止,我没有得到好的结果。有人能帮我做这个吗?
编辑
关于这个问题,我想我已经有所进展了。。。但当我运行它时,输出屏幕仍然崩溃。这是我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main () {
// string toks[];
char oneline[80],*del;
string line, creds[4];
int x = 0;
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++;
}
}
myfile.close();
}
else
cout << "Unable to open file";
system("pause");
}
有人能帮我解释一下吗?
编辑。。。。
我在这方面有一些进展。。。现在的问题是,当输入与下一行匹配时,它会崩溃。。。
#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");
}
有人能帮我做这个吗?
您可以使用boost令牌化器进行以下操作:
#include <boost/tokenizer.hpp>
typedef boost::char_separator<char> separator_type;
boost::tokenizer<separator_type> tokenizer(my_text, separator_type(","));
auto it = tokenizer.begin();
while(it != tokenizer.end())
{
std::cout << "token: " << *it++ << std::endl;
}
另请参阅getline以一次解析文件中的一行。
int main ()
{
ifstream file("file.txt");
string line;
while (getline(file, line))
{
stringstream linestream(line);
string item;
while (getline(linestream, item, ','))
{
std::cout << item << endl;
}
}
return 0;
}
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- 如何将来自文本文件的数据读取到结构的int阵列中
- 如何将不同长度的数据读取到 2D 数组中
- 从TXT文件到C 的结构向量中的数据读取
- 将sqlite原始数据读取到qbyTearray
- 如何将来自输入TXT文件的数据读取到2 C 数组中
- 使用MQQueue将数据读取到缓冲区中时麻烦
- 在 VC++ 中将类数据读取和写入二进制文件
- 将数据从数据读取器终端获取到GUI(QtCreator)
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- C++将二进制数据读取到结构
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 对齐数据:速度取决于恒定数据读取的相对采样大小和采样频率
- 如何将文件中的数据读取到数组中
- 如何使用Visual C++应用程序的完整应用程序数据读取Minidump的应用程序数据
- 如何将csv文件数据读取到数组中
- 用C++将格式化的数值数据读取到数组中
- 正在从文件中将数据读取到结构数组中
- 将分离的数据读取到数组结构c++中