代码在这里:http://ideone.com/AZnXFm
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char *buffer;
size_t bufsize = 32;
size_t characters;
buffer = (char *)malloc(bufsize * sizeof(char));
if( buffer == NULL)
{
perror("Unable to allocate buffer");
exit(1);
}
printf("Type something: ");
characters = getline(&buffer,&bufsize,stdin);
printf("%zu characters were read.\n",characters);
printf("You typed: %s",buffer);
char *end_str,*token2;
char *token = strtok_r(buffer,";",&end_str);
printf("token : %s \n", token);
int count =0,wordcnt=0;
while(token !=NULL)
{
char *end_token;
count++;
printf("outside count ------------------------%d\n", count);
strtok_r(token," ",&end_token);
while(token2!=NULL)
{
wordcnt++;
printf("insdie count %d\n",wordcnt);
printf("%s------------------- \n", token2);
token2 = strtok_r(NULL," ",&end_token);
}
token = strtok_r(NULL, ";",&end_str);
}
return(0);
}
输出是
Type something: rosie is; really good
22 characters were read.
You typed: rosie is; really good
token : rosie is
outside count ------------------------1
insdie count 1
AWAVA��AUATL�% -------------------
insdie count 2
is-------------------
outside count ------------------------2
最佳答案
下面的代码需要或已经应用了许多基本修复:
- 让
getline()
进行内存分配。 - 检查
getline()
是否读取了一行。 - 释放分配的内存。
- 使用内部
strtok_r()
调用设置token2
。 - 让变量名更系统一些。
- 将
characters
转换为ssize_t
以匹配getline()
的返回值。 - 使用
%zd
打印字符
。这是有争议的。它使用z
限定的有符号十进制格式字符串打印size_t
的有符号变体。这是有道理的(至少对我和我的编译器 — macOS Sierra 上的 GCC 6.2.0),但我不确定在哪里可以找到它被(POSIX)标准正式认可的确认。 - 重命名变量以保持一致性。
- 其他小的外观修复(打印格式仍然可以改进 — 相当多)。
导致:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *buffer = 0;
size_t bufsize = 0;
ssize_t characters;
printf("Type something: ");
characters = getline(&buffer, &bufsize, stdin);
printf("%zd characters were read.\n", characters);
if (characters > 0)
{
printf("You typed: %s", buffer);
char *end_str1;
char *token1 = strtok_r(buffer, ";", &end_str1);
printf("token: %s \n", token1);
int count = 0, wordcnt = 0;
while (token1 != NULL)
{
char *end_str2;
count++;
printf("outside count ------------------------%d\n", count);
char *token2 = strtok_r(token1, " ", &end_str2);
while (token2 != NULL)
{
wordcnt++;
printf("inside count %d\n", wordcnt);
printf("%s------------------- \n", token2);
token2 = strtok_r(NULL, " ", &end_str2);
}
token1 = strtok_r(NULL, ";", &end_str1);
}
}
free(buffer);
return(0);
}
运行示例:
Type something: rosie is; really good
22 characters were read.
You typed: rosie is; really good
token: rosie is
outside count ------------------------1
inside count 1
rosie-------------------
inside count 2
is-------------------
outside count ------------------------2
inside count 3
really-------------------
inside count 4
good
-------------------
关于c - 嵌套 strtok_r : command line argument parsing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39643072/