我从文件中提取数据:
sscanf (match, "cpu %d %d %d...", &user1, &nice1, &kernel1, &idl...);
当我尝试在循环中读取N个内核时,我的问题就出现了:
sscanf (match, "cpu0 %d %d..", &user1, &nic...);
sscanf (match, "cpu1 %d %d..", &user1, &nic...);
sscanf (match, "cpu2 %d %d...", &user1, &nic...);
有没有办法在C中将这个sscanf插入十进制变量?
编辑: 我想在" cpu"旁边增加数字。字符串得到" cpu 0 %d%d"," cpu 1 %d%d"," cpu 2 %d%d"
Edit2 +解决方案:
/* Locate the line that starts with "cpuX " */
match = strstr (buffer, cpux);
/* Parse the line and extract data */
sscanf (match, "%s %d %d %d %d %d %d %d %d %d %d", *&cpuXgarbage,&...)
答案 0 :(得分:2)
有,但这可能是错误的做法。
不是将cpu0放在你的sscanf字符串中,为什么不用%s?将cpu0读入字符串。那么它是否匹配并不重要。你可以有一个读取循环来查找" cpu"在开始和停止时它不匹配。
答案 1 :(得分:2)
for (int i=0; i < 10; i++) {
sprintf(format, "cpu%d blah blah", i);
sscanf(match, format, ...);
}
答案 2 :(得分:0)
int user[20];
int nic[20];
int i = 0;
sscanf (match, "cpu0 %d %d..", &(user[i++]), &(nic[i++])...);
sscanf (match, "cpu0 %d %d..", &(user[i++]), &(nic[i++])...);
.....