C 用户的预期输入是3个字符串,但若用户只给出2个字符串,那个么我希望代码继续
问题是,我希望用户输入3个字符串,但如果用户只输入2个字符串,我的代码将停止,因为它希望再输入1个字符串。但我需要我的代码以仅使用2个字符串继续。因此,我应该做哪些更改C 用户的预期输入是3个字符串,但若用户只给出2个字符串,那个么我希望代码继续,c,string,C,String,问题是,我希望用户输入3个字符串,但如果用户只输入2个字符串,我的代码将停止,因为它希望再输入1个字符串。但我需要我的代码以仅使用2个字符串继续。因此,我应该做哪些更改 `enter code here` #include <stdio.h> #include <ctype.h> int main() { char a[100]; char b[100]; char c[100]; printf("enter your name\n")
`enter code here`
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[100];
char b[100];
char c[100];
printf("enter your name\n");
scanf("%s %s %s",a,b,c);
printf("%c%c%c",toupper(a[0]),toupper(b[0]),toupper(c[0]));
return 0;
}
`在此处输入代码`
#包括
#包括
int main()
{
chara[100];
charb[100];
charc[100];
printf(“输入您的姓名”);
scanf(“%s%s%s”,a、b、c);
printf(“%c%c%c”,toupper(a[0]),toupper(b[0]),toupper(c[0]);
返回0;
}
根据以下人员的建议:
#包括
#包括
#包括
#定义缓冲区大小300
int main()
{
字符字符串[3][100]={{},
{},
{}};
char cInputBuffer[缓冲区大小];
常量字符delimeter[2]=“”;
字符*令牌;
int i=0;
printf(“输入您的姓名”);
scanf(“%[^\n]”,cInputBuffer);
令牌=strtok(cInputBuffer,delimeter);
while(令牌!=0&&i<3)
{
sprintf(字符串[i],“%.100s”,令牌);
令牌=strtok(空,delimeter);
i++;
}
如果(i>1)
{
printf(“%c%c%c”、toupper(字符串[0][0])、toupper(字符串[1][0])、toupper(字符串[2][0]);
}
其他的
{
printf(“至少输入个人和姓氏”);
}
返回0;
}
“我应该做什么更改”-答案太多,因此一般来说太宽泛。让他们输入一个字符串,然后使用strtok
解析。确保防止缓冲区溢出,这是您当前易受攻击的问题。请阅读一行并自行解析。应该有人编写“输入一个字符串并解析它”想法作为答案-可能是@JohnColeman,因为他是第一个,因此应该得到分数。@JeremyP我现在太累了,无法添加任何细节,请随意发布。谢谢你,我非常感谢你的帮助,因为我从这段代码中学到了一个新函数。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define BUFFER_SIZE 300
int main()
{
char strings[3][100] = {{},
{},
{}};
char cInputBuffer[BUFFER_SIZE];
const char delimeter[2] = " ";
char* token;
int i = 0;
printf("Enter your name\n");
scanf("%[^\n]", cInputBuffer);
token = strtok(cInputBuffer, delimeter);
while( token != 0 && i < 3)
{
sprintf(strings[i],"%.100s",token);
token = strtok(NULL, delimeter);
i++;
}
if(i > 1)
{
printf("%c%c%c",toupper(strings[0][0]),toupper(strings[1][0]),toupper(strings[2][0]));
}
else
{
printf("Enter at least personal and family name.");
}
return 0;
}