【发布时间】:2013-04-25 00:34:14
【问题描述】:
我想要做的是获取一个大输入(读取直到用户按下 enter(\n)),然后调用一个函数来放置这个输入的第一个单词(读取到'')。我的问题是,即使它看起来很简单,它也有 2 个额外的外星人字符。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void findChoise(char *input, char *choise);
int main()
{
char choise[12];
char input[300];
printf("give me the input: ");
gets(input);
printf("%s\n", input);
printf("%s%d\n", "length of input: ", strlen(input));//for checking
findChoise(input, choise);
printf("%s%d\n", "length of output: ", strlen(choise));//for checking
printf("%s\n", choise);
return 0;
}
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
};
}
【问题讨论】:
-
您确实希望使用
fgets()以确保安全,使用strchr()以保持简洁。 (哦,const char *表示 const 的正确性,在适当的情况下。)