[英]how to token a full line input in c?
I need to parse a line from cmd that looks like this 我需要从cmd解析一条看起来像这样的行
"SOME WHITE SPACE" "var_name" "SOME WHITE SPACE" "var_value" "SOME WHITE SPACE"
i take the whole line with fgets: 我把整个行与fgets:
fgets(input_buf,MAX_LINE_LENGTH,stdin);
and tried to tokenize like this: 并尝试像这样标记化:
sscanf(input_buf,"%s", var_buff);
sscanf(input_buf+strlen(var_buff),"%s", var_val_buff);
sscanf(input_buf+(strlen(var_buff)+strlen(var_val_buff)+2),"%s", rest_line_buff);
if (strlen(rest_line_buff) == 0)
printf("error in usage\n");
I dont get the right values as the number of white spaces may vary. 由于空格的数量可能会变化,因此我无法获得正确的值。 how can i tokenize the input line? 如何标记输入行?
Use strtok
, as shown in the sample program below: 使用strtok
,如下面的示例程序所示:
#include <stdio.h>
#include <string.h>
int main ()
{
char sampleInput[] ="foo bar foo1 bar1 foo2 bar2";
char *token;
char *whiteSpace = " \t\n\f\r\v";
int isVariable = 1;
token = strtok(sampleInput, whiteSpace);
while (token != NULL)
{
if (isVariable)
printf("Variable = %s\n", token);
else
printf("Value = %s\n\n", token);
isVariable = isVariable ? 0 : 1;
token = strtok(NULL, whiteSpace);
}
return 0;
}
Output: 输出:
Variable = foo
Value = bar
Variable = foo1
Value = bar1
Variable = foo2
Value = bar2
All functions from the scanf family aggregate and skip multiple whitespace characters by default: scanf系列中的所有函数默认都会聚合并跳过多个空格字符:
sscanf(input_buf," %s %s", var_buff, var_val_buf);
I am not sure the leading whitespace in the format string is strictly necessary, but I am positive that it is correct event if there is no actual whitespace at the beginning of the input line. 我不确定格式字符串中的前导空格是否绝对必要,但是如果输入行的开头没有实际的空格,我肯定这是正确的事件。
使用扫描仪生成器: http : //en.wikipedia.org/wiki/Lexical_analysis#Lexer_generator或下载令牌生成器库。
It seems to natural to use strtok( )
or strtok_r( )
here. 在这里使用strtok( )
或strtok_r( )
很自然。 Why have you decided against it? 你为什么反对呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.