我创建了一个输入用户名称并输出其首字母的函数。例如,“John Doe”应该是JD,而“Rick Dixon Lightning”应该是RDL。它甚至应该处理杂乱的条目,例如“geoRge 6w bu7sh”,返回“GWB”。
以下代码功能完美,但有一个问题:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
printf("Your name: ");
string name = GetString();
int nameLength = strlen(name);
int initials[nameLength];
int initialSwitch = 0;
for (int i = 0; i < nameLength; i++)
{
if(initialSwitch%2 == 0 && (int)name[i] != 32 && tolower(name[i]) >= 97 && tolower(name[i])<=122)
{
initials[initialSwitch] = (int)name[i];
initialSwitch++;
} else if(initialSwitch%2!=0 && (int)name[i] == 32){
initialSwitch++;
}
}
for (int i = 0; i<initialSwitch; i++)
{
printf("%c",toupper(initials[i]));
}
printf("\n");
}
底部输出循环单独输出每个初始值,而我需要将首字母输出为单个串联字符串。我已经浏览了互联网,并提出了我最好的解决方案,遗憾的是,该解决方案无法正常运行:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
printf("Your name: ");
string name = GetString();
int nameLength = strlen(name);
char initials[nameLength];
int initialSwitch = 0;
for (int i = 0; i < nameLength; i++)
{
if(initialSwitch%2 == 0 && (int)name[i] != 32 && tolower(name[i]) >= 97 && tolower(name[i])<=122)
{
initials[initialSwitch] = (int)name[i];
initialSwitch++;
} else if(initialSwitch%2!=0 && (int)name[i] == 32){
initialSwitch++;
}
}
initials[initialSwitch]=(int)"\0";
for (int i = 0; i<initialSwitch; i++)
{
printf("%s\n",initials);
}
}
对于测试输入“John Bill Doe”,我尝试的解决方案输出“j \ nj \ nj \ nj \ nj \ n”或五个“j”,每个都在各自的行上。
我在这里弄错了什么?
编辑:
答案 0 :(得分:0)
感谢大家的帮助。总而言之,我犯了以下错误:
以下工作代码:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
printf("Your name: ");
string name = GetString();
int nameLength = strlen(name);
char initials[nameLength];
int initialSwitch = 0;
int initialCount = 0;
for (int i = 0; i < nameLength; i++)
{
if(initialSwitch%2 == 0 && name[i] != 32 && tolower(name[i]) >= 97 && tolower(name[i])<=122)
{
initials[initialCount] = toupper(name[i]);
initialSwitch++;
initialCount++;
} else if(initialSwitch%2!=0 && name[i] == 32){
initialSwitch++;
}
}
initials[initialCount]='\0';
printf("%s\n",initials);
}