如何将这个log.txt文本文件读入我的程序中的结构? (C ++) ////////////////////////logs.txt/////////////////////// /////
Port4000.txt:M:r:10
Port4001.txt:M:w:1
Port4002.txt:M:w:9
Port4003.txt:J:x:1
代表:
Port40xx.txt代表端口号 : M代表用户 : r代表行动 : 10代表阈值
/////////////////////////////////////////////// ////////////
struct Pair
{
char user;
char action;
}
int main()
{
Pair pairs;
ifstream infile;
char portnumber[20];
infile.open("logs.txt",ios::in); // `open the log text file `
infile.getline(portnumber,20,':'); //`Reading the portnumber of the user and action
`
infile >> pairs.user >> pairs.action >> threshold;
//`THE PROBLEM IS HOW TO read the user, action, threshold whenever it meets ":" symbol?`
infile.close();
return 0;
}
如果有任何方法可以阅读char数据类型,请告诉我,直到它符合":"符号并开始读取另一个char数据类型。谢谢:))
答案 0 :(得分:1)
你可以继续做你为“portnumber”做的事情:
<强> Live On Coliru 强>
#include <fstream>
#include <iostream>
struct Pair {
char user;
char action;
};
int main()
{
std::ifstream infile;
infile.open("logs.txt", std::ios::in); // `open the log text file `
std::string portnumber, user, action, threshold;
if (getline(infile, portnumber, ':')
&& getline(infile, user, ':') && user.size() == 1
&& getline(infile, action, ':') && action.size() == 1
&& getline(infile, threshold, '\n'))
{
Pair pair { user[0], action[0] };
}
}
请注意std::getline
的使用比std::istream::getline