我正在尝试编写一个 C 程序来使用字符串和指针打印最终用户姓名的首字母。我在评论中写下了我认为该功能需要做的事情以供说明。
这是我目前的进展:
#include <stdio.h>
#include <string.h>
#define MAX_BUFFER_LENGTH 31
char userInitials(char *name)
{
// Initialize the character array "name" and set to zero
// Determine the length of the string using strlen
// Print the first valid input of the string
// Loop through the string until a space is found
// When a space is found, print the next valid input
for (int i = 0; i < MAX_BUFFER_LENGTH; i++)
{
name[i] = 0;
}
int length = strlen(name);
if (name[0] != ' ' && name[0] != '\0')
{
printf("%c\n", name[0]);
}
for (int i = 0; i < length; i++)
{
if (i + 1 < length && name[i + 1] != ' ')
{
printf("%c\n", name[i + 1]);
}
}
}
char main()
{
char name[MAX_BUFFER_LENGTH] = " ";
printf("Enter your full name and I'll print your initials: ");
scanf_s("%[^\n]", &name, MAX_BUFFER_LENGTH);
printf("Your name is: %c\n", name);
printf("Your initials are: %c\n", userInitials(name));
}
我的程序目前卡在第 42 行:
printf("Your initials are: %s\n", userInitials(name));
Visual Studio 返回一条错误消息:
(42): warning C4477: 'printf' : format string '%s' requires an argument of type 'char *', but variadic argument 1 has type 'int'.
我也不确定该函数是否有效,因为第 33 行有一个我不明白的错误(我发布第 26-33 行以供说明):
for (int i = 0; i < length; i++)
{
if (i + 1 < length && name[i + 1] != ' ')
{
printf("%c\n", name[i + 1]);
}
}
}
Visual Studio 正在返回一条错误消息:(33):警告 C4716:“userInitials”:必须返回一个值。
我真的很难让它正常工作,而且我的导师不太擅长解释如何解决错误消息。非常感谢您的宝贵时间和帮助。
最佳答案
Printf 格式字符串参数 %s
需要一个指向 char 的指针。
您的函数返回一个字符(不是指针),
至少原型(prototype)是这样 promise 的,即使当时的代码没有。
消息告诉你的很清楚。
为了打印单个字符,使用%c
。
您的函数 userInitials()
不返回任何内容,因为它不包含单个 return
语句,这是您问题第二部分的原因.
AlexeiLevenkov(在上面的评论中)提供了一个有用的链接,指向讨论此错误的 Microsoft 内容,其中包含带有注释的 return
的函数示例:
https://learn.microsoft.com/en-us/previous-versions/ft5xye74(v=vs.140)
(顺便说一句,在 StackOverflow 上,一次只询问一个问题更受欢迎。询问不止一件事的问题可能会因为过于宽泛而被关闭。)
关于打印字符串中单词首字母的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690365/