我正在尝试通过使用scanf运算符来获取输入,但是我也需要它的长度,我无法定义,char name[number]
因为我不知道从用户那里得到的输入的大小...
有什么想法不使用怎么办string.h
?
这是我尝试做的事情,但是由于定义了数组的长度,因此是非法的:
char string1[30];
printf("Enter string1:");
scanf("%s",string1);
如果不定义最大大小,您可能不会相处。
重要的是不定义大小,但事后知道并尊重它。
从用户那里获取输入的最简单方法是fgets()
:
char string1[50];
fgets(string1, sizeof string1, stdin);
当然,您应该检查其返回值。
如果您想(几乎)接受任何长度,都可以尝试我在这里给出的解决方案。
这是防止给定数组溢出的必要条件。为了使用该字符串,您可以使用来缩短其长度strlen()
,或者,如果不允许使用该字符串,或者仍然要走到字符串上,则可以对字符进行计数,直到达到NUL字节为止。
其背景是C中的字符串以NUL字节终止。它们是char
s的序列,并且NUL字节(0,而不是'0'
48)终止该序列。
如果您唯一的任务是验证读取的字符串是否足够小,然后抱怨,则只需:-)
int main(int argc, char ** argv)
{
char string2[50]; // larger than required; in order to be able to check.
char string1[30]; // if all is ok, you have maximum length of 29, plus the NUL terminator. So 30 is ok.
char * ret = fgets(string2, sizeof string2, stdin);
if (!ret) {
fprintf(stderr, "Read error.\n")
return 1; // indicate error
}
if (strlen(string2) >= sizeof string1) { // we can take this size as a reference...
fprintf(stderr, "String 1 too long.\n")
return 1; // indicate error
}
strcpy(string1, string2); // as we have verified that this will match, it is ok.
// Otherwise, we would have to use strncpy.
// Now read the 2nd string by the same way:
ret = fgets(string2, sizeof string2, stdin);
if (!ret) {
fprintf(stderr, "Read error.\n")
return 1; // indicate error
}
if (strlen(string2) >= sizeof string1) { // we can take this size as a reference...
fprintf(stderr, "String 2 too long.\n")
return 1; // indicate error
}
// Now we know that both strings are ok in length an we can use strcmp().
int c = strcmp(string1, string2);
printf("strcmp() result: %d.\n", c);
return 0; // indicate success
}
现在还不清楚您是否也应该执行strcmp()
。如果是这样,我将其保留为练习。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句