Pet*_*oip 5 c string stdin scanf
我是C的新手,我正在尝试从标准输入扫描一行并从中提取第n个单词.现在我已经对它进行了硬编码,你可以在句子中存储第一个,第二个或第三个条目,这就是它的样子:
int set_to_nth_word(char* word, char* input, int n)
{
char word1[20];
char word2[20];
char word3[20];
if(sscanf(input, "%s %s %s", word1, word2, word3) < n)
{
printf("You didn't enter enough values\n");
return 0;
}
else
{
if(n == 1) strcpy(word, word1);
else if(n == 2) strcpy(word, word2);
else if(n == 3) strcpy(word, word3);
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
调用此方法的代码是:
char *input = (char *) malloc (1);
if(getline(&input, (size_t)0, stdin) != -1)
{
char word[20];
if(set_to_nth_word(word, input, 1))
{
printf("Success");
}
}
Run Code Online (Sandbox Code Playgroud)
除了找到解决这个问题的方法之外,如果有人指出任何不好的风格或糟糕的编码习惯,我会很高兴!
您可以使用%n支持的转换说明符sscanf().它需要一个int *参数,并返回从输入中消耗的字符数int.
int set_to_nth_word(char *word, const char *input, int n)
{
int chars_used;
word[0] = '\0'; /* In case n < 1 */
while (n > 0 && sscanf(input, "%s%n", word, &chars_used) > 0)
{
input += chars_used;
n--;
}
if (n > 0)
{
printf("You didn't enter enough values\n");
return 0;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
就样式而言,您应该创建input参数const char *,因为指向的字符未在函数中被修改.
在安全性方面,word应该分配长度strlen(input) + 1,而不是声明为固定大小的数组,因为单词可能达到该长度.