如何在c中标记整行输入?
我需要解析 cmd 中的一行,看起来像这样,
"SOME WHITE SPACE" "var_name" "SOME WHITE SPACE" "var_value" "SOME WHITE SPACE"
我用 fgets: 获取整行:
fgets(input_buf,MAX_LINE_LENGTH,stdin);
并尝试像这样标记:
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 need to parse a line from cmd that looks like this
"SOME WHITE SPACE" "var_name" "SOME WHITE SPACE" "var_value" "SOME WHITE SPACE"
i take the whole line with 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
strtok
,如示例程序所示如下:输出:
Use
strtok
, as shown in the sample program below:Output:
scanf 系列中的所有函数默认聚合并跳过多个空格字符:
我不确定格式字符串中的前导空格是否是绝对必要的,但我确信如果在开头没有实际的空格,则这是正确的事件输入线。
All functions from the scanf family aggregate and skip multiple whitespace characters by default:
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 或者,下载分词器库。
Use a scanner generator: http://en.wikipedia.org/wiki/Lexical_analysis#Lexer_generator or, download a tokenizer library.
在这里使用
strtok( )
或strtok_r( )
似乎很自然。你为什么决定反对?It seems to natural to use
strtok( )
orstrtok_r( )
here. Why have you decided against it?