我有一个类似于/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‘表示字符串不同,因此断言失败。无论如何,我只想保留这些值的内存,而不会耗尽我不需要的内存。我需要做些什么才能让它正常工作呢?
发布于 2011-03-11 18:59:23
sscanf太C了。
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";
}
}
}发布于 2011-03-11 19:23:03
如果您使用的是c++,我会尝试使用std::string、iostreams以及C++附带的所有这些东西,但是再次...
我理解您的问题是C字符串中的一个是空终止的,而另一个不是,然后strcmp单步执行到一个字符串上的'\0',但另一个字符串有另一个值……如果这是您唯一想要更改的内容,请使用与已知字符串长度相同的strncpy。
发布于 2011-03-11 18:56:21
我不认为strcmp有问题,但是您的sscanf格式有一个问题。%s将读取到第一个非白色字符,因此它将读取:。您可能希望将"%50[^:]:%55[^:]:%30s"作为格式字符串。我已经添加了字段大小,以防止缓冲区溢出,但我可能会在限制中减少一个。
https://stackoverflow.com/questions/5271912
复制相似问题