如何确保用户输入是唯一的
How to make sure user input is unique
在我的程序中,我想确保用户输入的 'identifier' 字符串对于他们正在创建的新 Book 对象是唯一的。我认为 While 循环是可行的方法,并让它不断要求用户输入标识符,直到它与现有标识符不匹配为止。真的很难找到一种方法让它发挥作用,所以如果有人能指出我正确的方向,我将非常感激。谢谢!
我顺便用了一个链表结构..
void addBook(){
struct node *aNode;
struct book *aBook;
struct node *current, *previous;
bool identifierIsTaken = true;
char identifierInput[10];
current = previous = front;
aBook = (struct book *)malloc(sizeof(struct book));
while(identifierIsTaken){
printf("Enter identifier for new book: ");
scanf("%s", identifierInput);
if(!strcmp(identifierInput, current->element->identifier) == 0){
identifierIsTaken = false;
strncpy(aBook->identifier, identifierInput, 10);
}
else
previous = current;
current = current->next;
}
printf("Enter book name: ");
scanf("%s", &aBook->name);
printf("Enter author: ");
scanf("%s", &aBook->author);
........
当我输入一个占用的标识符时,循环似乎只工作一次,但如果我再次尝试,它就会失败并使用标识符。
最好单独编写一个函数来检查标识符是否唯一。
int isUnique(char *identifierInput,struct node start)
{
while(start != NULL) {
if(strcmp(identifierInput, start->element->identifier) == 0) {
//string already present,return 0.
return 0;
}
start = start->link;
}
//we reached end of linked list.string is unique.return 1.
return 1;
}
从你的 main 你调用这个函数,
sudo 代码
int main()
{
:
:
:
while(i<number_of_item){
printf("Enter identifier for new book: ");
scanf("%s", identifierInput);
if(isUnique(identifierInput,current)){
//add it to the linked list.do whatever you want here.
} else {
// it is not unique.do what ever you want here.
}
}
:
:
:
}
希望对您有所帮助。
在我的程序中,我想确保用户输入的 'identifier' 字符串对于他们正在创建的新 Book 对象是唯一的。我认为 While 循环是可行的方法,并让它不断要求用户输入标识符,直到它与现有标识符不匹配为止。真的很难找到一种方法让它发挥作用,所以如果有人能指出我正确的方向,我将非常感激。谢谢!
我顺便用了一个链表结构..
void addBook(){
struct node *aNode;
struct book *aBook;
struct node *current, *previous;
bool identifierIsTaken = true;
char identifierInput[10];
current = previous = front;
aBook = (struct book *)malloc(sizeof(struct book));
while(identifierIsTaken){
printf("Enter identifier for new book: ");
scanf("%s", identifierInput);
if(!strcmp(identifierInput, current->element->identifier) == 0){
identifierIsTaken = false;
strncpy(aBook->identifier, identifierInput, 10);
}
else
previous = current;
current = current->next;
}
printf("Enter book name: ");
scanf("%s", &aBook->name);
printf("Enter author: ");
scanf("%s", &aBook->author);
........
当我输入一个占用的标识符时,循环似乎只工作一次,但如果我再次尝试,它就会失败并使用标识符。
最好单独编写一个函数来检查标识符是否唯一。
int isUnique(char *identifierInput,struct node start)
{
while(start != NULL) {
if(strcmp(identifierInput, start->element->identifier) == 0) {
//string already present,return 0.
return 0;
}
start = start->link;
}
//we reached end of linked list.string is unique.return 1.
return 1;
}
从你的 main 你调用这个函数,
sudo 代码
int main()
{
:
:
:
while(i<number_of_item){
printf("Enter identifier for new book: ");
scanf("%s", identifierInput);
if(isUnique(identifierInput,current)){
//add it to the linked list.do whatever you want here.
} else {
// it is not unique.do what ever you want here.
}
}
:
:
:
}
希望对您有所帮助。