我是一名 C 菜鸟,要回到学校攻读 CS 硕士学位,所以我需要一些时间来提高我的技能。我想看看是否有人可以为我在编译以下代码时遇到问题提供一些帮助。我一直在关注 WiBit.net 上的视频并在 64 位 Linux 环境(Ubuntu 13.10)上进行开发。我正在使用 gedit 和 gcc 编译器,没有 IDE。
此代码在我的 Win 7 VM 上运行没有错误,但是当我尝试在主机 Linux 环境上执行它时,我收到错误:
源代码:本示例调用 strcmp 和 strcmpi 函数
#include <stdio.h>
#include <string.h>
int main()
{
char str1[255];
char str2[255];
printf("str1: "); gets(str1);
printf("str2: "); gets(str2);
if(strcmp(str1, str2) == 0)
printf("Strings match exactly!");
else if(strcmpi(str1, str2) == 0)
printf("Strings match when ignoring case!");
return 0;
}
错误消息(仅限 Linux):
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
/tmp/ccwqdQMN.o:在函数中 main':
main.c:(.text+0x25): warning: the
gets' 函数是危险的,不应使用。
main.c:(.text+0x8f): 对“strcmpi”的 undefined reference
collect2:错误:ld 返回 1 退出状态
源代码 2:此示例使用 strupr 和 strlwr 函数
#include <stdio.h>
#include <string.h>
int main()
{
char str1[255];
char str2[255];
printf("str1: "); gets(str1);
printf("str2: "); gets(str2);
strlwr(str1);
strupr(str2);
puts (str1);
puts (str2);
return 0;
}
错误消息(仅限 Linux):
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
/tmp/ccWnIfnz.o:在函数 main':
main.c:(.text+0x25): warning: the
中gets' 函数是危险的,不应使用。
main.c:(.text+0x57): 对 strlwr'
main.c:(.text+0x6b): undefined reference to
的 undefined reference 斯特鲁普尔
collect2:错误:ld 返回 1 退出状态
如果有人愿意帮助而不是拆散我,我希望得到详细的解释,哈哈。我知道,对于最佳实践,我们不应该因缓冲区溢出而使用 gets(例如用户输入 750 个字符的字符串)。最佳实践是使用 fgets,但我的问题是我收到这些错误是否是因为这些函数不是 ANSI C 的一部分或者什么。它们确实出现在我机器上的 man 文件中,这让我陷入了困境。
提前致谢!
更新: 你们太棒了。采纳了您的所有建议和意见,并能够修改并制作一个用于字符串比较以及大写/小写转换的示例程序。很高兴我能够让它在两个操作系统上运行并且没有错误。
示例代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char str[255];
printf("Enter a string: "); fgets(str,255, stdin);
printf("Here is your original string, my master: %s\n", str);
//Now let's loop through and convert this to all lowercase
int i;
for(i = 0; str[i]; i++)
{
str[i] = tolower(str[i]);
}
printf("Here is a lowercase version of your string, my master: %s\n", str);
//Now we'll loop through and convert the string to uppercase
int j;
for(j = 0; str[j]; j++)
{
str[j] = toupper(str[j]);
}
printf("Here is a uppercase version of your string, my master: %s\n", str);
return 0;
}
最佳答案
strcmpi问题:strcasecmp()是posix标准,linux中也是如此。
strupr 和 strlwr 在 glibc 中不存在,尽管您可以用一行代码实现它们,如下所示: c - convert a mixed-case string to all lower case
在编译时,首先会发现一个警告,因为gcc没有找到包含头文件中的函数。在这种情况下,它认为它们被声明为 int funcname(void)。但后来,在链接时,它找不到这个不存在的函数的导出符号,因此无法创建可执行文件。第二个错误导致编译停止。
c api 之间有太多差异,尽管 posix 标准处理它们,但微软不遵循它。
关于c - 初学 C 程序员在使用字符串函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20480578/