如果不定义最大尺寸,您可能无法相处。
不定义大小并不重要,重要的是事后了解并尊重它。
从用户那里获取输入的最简单方法是fgets():
char string1[50];
fgets(string1, sizeof string1, stdin);
当然,你应该检查它的返回值。
如果你想接受(几乎)任何长度,你可以试试the solution I gave here。
这是防止给定数组溢出所必需的。为了使用字符串,您可以使用strlen() 来获取它的长度,或者,如果您不允许使用它或正在走到字符串,则通过计数字符直到您遇到 NUL 字节。
其背景是 C 中的字符串以 NUL 字节终止。它们是chars 的序列,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()。如果是这样,我会把它留作练习。