因此我尝试使用sscanf读取字符串但它似乎没有读取任何内容。我跟着tutrial看起来非常相似。我无法理解它为什么不读任何东西。
int main(){
int status =0;
int ret = 0;
int arg;
char *cmdLine = NULL;
char *cmd=NULL;
size_t n = 0;
char *line = NULL;
char *token =NULL;
while (getline(&line, &n, stdin) > 0){
//toekenize line
token = strtok(line,";");
//go thorugh and scan for cmds
while(token !=NULL){
// printf("token=%s\n", token);
cmdLine = token;
printf("%s\n", cmdLine);
//read the commands
ret=sscanf(cmdLine, "%31s %d", cmd, &arg);
printf("%d\n", ret);
token = strtok(NULL, ";");
}//while loop 2
//set line and n back to null and 0.
line = NULL;
n = 0;
}//while loop 1
答案 0 :(得分:1)
试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int status =0;
int ret = 0;
int arg;
char *cmdLine = NULL;
char cmd[100];
size_t n = 0;
char *line = NULL;
char *token =NULL;
if (getline(&line, &n, stdin) > 0)
{
//toekenize line
token = strtok(line,";");
//go thorugh and scan for cmds
if(token != NULL)
{
// printf("token=%s\n", token);
cmdLine = token;
printf(">>>> %s \n", cmdLine);
//read the commands
ret = sscanf(cmdLine, "%s %d", cmd, &arg);
printf(">>>> %d \n", ret);
token = strtok(NULL, ";");
}//while loop 2
//set line and n back to null and 0.
line = NULL;
n = 0;
}//while loop 1
printf("Result string: %s and Arg: %d \n", cmd, arg);
}