gpt4 book ai didi

c++ - sscanf 多值 n 长度值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:01:57 25 4
gpt4 key购买 nike

我有一个类似于/etc/passwd(分号分隔值)的文件,需要将每行的所有三个值提取到变量中,然后将它们与程序中给出的值进行比较。这是我的代码:

  typedef struct _UserModel UserModel;
struct _UserModel {
char username[50];
char email[55];
char pincode[30];
};

void get_user(char *username) {
ifstream io("test.txt");
string line;
while (io.good() && !io.eof()) {
getline(io, line);
if (line.length() > 0 && line.substr(0,line.find(":")).compare(username)==0) {
cout << "found user!\n";
UserModel tmp;
sscanf(line.c_str() "%s:%s:%s", tmp.username, tmp.pincode, tmp.email);
assert(0==strcmp(tmp.username, username));
}
}
}

我无法对值进行 strcmp,因为尾随的“\0”表示字符串不同,因此断言失败。无论如何,我真的只想保留这些值的内存,而不是用完这些值不需要的内存。我需要更改什么才能使其正常工作..?

最佳答案

sscanf 太中国了。

struct UserModel {
string username;
string email;
string pincode;
};

void get_user(char *username) {
ifstream io("test.txt");
string line;
while (getline(io, line)) {
UserModel tmp;
istringstream str(line);
if (getline(str, tmp.username, ':') && getline(str, tmp.pincode, ':') && getline(str, tmp.email)) {
if (username == tmp.username)
cout << "found user!\n";
}
}
}

关于c++ - sscanf 多值 n 长度值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5271912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com