gpt4 book ai didi

c - 如何使用指针在 C 中的第一个空格上分割字符串?

转载 作者:行者123 更新时间:2023-11-30 14:36:55 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,允许用户输入他的全名,然后程序仅输出他的全名。为此,我创建了一个指针,其 malloc 大小为 128 个字符,用于稍后存储名称。

我尝试使用 CLion、Netbeans、Code Blocks 运行该程序,现在位于 this site ,但他们指出了一些错误...因此程序无法运行。

问题是程序甚至没有编译,说有一些错误......这些是构建消息:

|=== Build: Debug in exerciseSixteen (compiler: GNU GCC Compiler) ===|
| LINE | MESSAGE
| |In function 'getSurname':
| 08 |warning: initialization makes integer from pointer without a cast [-Wint-conversion]
| |In function 'main':
| 04 |error: expected ')' before numeric constant
| 17 |note: in expansion of macro 'MAX'
| 21 |warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]|
|=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

我什至卸载了 MinGW 编译器和 MSyS,并重新安装了同时安装 MinGW 的 CodeBlocks,但现在我知道我的问题与编译器或 IDE 无关......这可能是代码,由方式,见下图:

#include <stdio.h>
#include <stdlib.h>

#define MAX 128

char *getSurname(char *name)
{
char space = " ";
while (*name!=space) {
name++;
}
return name;
}

int main()
{
char *name = malloc(sizeof(char*MAX));
printf("Insert your full name: ");
gets(name);
char surname = *getSurname(name);
printf("Hello %s!\n", surname);
return 0;
}

我在这段代码上看不到任何错误,我坚持认为一切都好......我错过了什么?我该怎么做才能让它正常工作?

最佳答案

嗯,有几个错误:

  1. malloc(sizeof(char*MAX) 应为 malloc(sizeof(char) * MAX)
  2. gets() 不应该永远使用,请使用 fgets(name, MAX, stdin)
  3. char space = ""; 是错误的,应该是 char space = ' ';,因为 "" 是一个字符串,不是一个角色。
  4. char surname = *getSurname(&name) 也有两个错误:第一,不需要使用 *,必须声明 姓氏char *,而不是char;其次,您也不需要使用 &name 。正确的调用是 char *surname = getSurname(name);
  5. 在扫描 name 时,您还必须检查 '\0',以避免超出字符串末尾。
  6. 您停在while中的空格处,您应该再前进一个字符,在返回之前添加一个name++,以防找到空格。
  7. 您应该检查malloc()的返回值,如果返回NULL,则退出程序。
  8. 在从 main 返回之前 free(name) 是一个很好的做法,尽管这并不是严格需要的。

正确的代码是:

#include <stdio.h>
#include <stdlib.h>

#define MAX 128

char *getSurname(char *name)
{
while (*name != '\0' && *name != ' ')
name++;

if (*name == ' ')
name++;

return name;
}

int main(void)
{
char *name = malloc(sizeof(char) * MAX);
if (name == NULL) {
perror("malloc() failed");
return 1;
}

printf("Insert your full name: ");
fgets(name, MAX, stdin);

char *surname = getSurname(name);
printf("Hello %s!\n", surname);

free(name);
return 0;
}

此外,作为旁注,fgets() 在第一个换行符处停止,因此您应该在处理之前从名称中删除换行符,否则您将得到如下输出:

Hello Relbeits
!

您可以在调用fgets()后执行此操作:

char *nl = strchr(name, '\n');
if (nl != NULL)
*nl = '\0';

关于c - 如何使用指针在 C 中的第一个空格上分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com