我正在使用带有do while语句的名称之前使用 Mr 或 ms 或 Mrs 进行输入名称的验证。我应该在while部分填写什么?
它是使用 strcmp 还是其他东西?
编码示例
do{
printf("Input Customer's Name [must have Mr. or Ms. or Mrs");
scanf("%[^\n]", &customerName);
}while(what should i fill here?);
编写一个单独的函数来检查名称是否以列出的字符串开头。
例如
#include <stdio.h>
#include <string.h>
int start_with( const char *s, const char * a[] )
{
int success = 0;
s += strspn( s, " \t" );
for ( ; *a != NULL && !success; ++a )
{
success = memcmp( s, *a, strlen( *a ) ) == 0;
}
return success;;
}
int main(void)
{
const char *title[] = { "Mr.", "Ms.", "Mrs.", NULL };
enum { N = 100 };
char name[N];
do
{
printf( "Input Customer's Name [must have %s or %s or %s: ", title[0], title[1], title[2] );
name[0] = '\0';
fgets( name, N, stdin );
name[strcspn( name, "\n" )] = '\0';
} while ( !start_with( name, title ) );
puts( name );
return 0;
}
程序输出可能看起来像
Input Customer's Name [must have Mr. or Ms. or Mrs.: Bob
Input Customer's Name [must have Mr. or Ms. or Mrs.: Mr. Bob
Mr. Bob
您需要检查子字符串'Mr.' '太太。' 或“Ms”是否存在于用户提供的输入字符串中。如果存在,您可以跳出循环,否则再次提示他/她。
需要注意的一点是,这个问题中的子字符串位置必须为0(即在输入字符串的最开头)
您可以使用strstr函数,因为它不仅检查子字符串,而且还返回指向第一次出现的指针。
例如
#include <stdio.h>
int main(void) {
char customerName[50];
char *titles[3] = {"Mr.","Mrs.","Ms."};
char *titlePos;
int istitle = 0;
do{
printf("Input Customer's Name [must have Mr. or Ms. or Mrs \n");
scanf("%[^\n]%*c",customerName);
for(int i=0;i<3 && !istitle;i++){
// checking if any of the title is present
titlePos=strstr(customerName,titles[i]);
if(titlePos && (int)(titlePos-customerName)==0) {
istitle=1; // title found
printf("CustomerName Consist the Title of %s \n",titles[i]);
}
}
}while(!istitle);
// ... Rest of Your Code
return 0;
}
如果您坚持只更改what should i fill here?
编码示例中getchar()
的 但通常情况下,人们会scanf()
使用格式字符串"%[^\n]\n"
或"%[^\n] "
(等效)来正确执行此操作。
除此之外,表达式
strncmp("Mr.", customerName, 3) &&
strncmp("Ms.", customerName, 3) &&
strncmp("Mrs", customerName, 3)
会做。