我试图理解指针,结构等的整个概念,所以我创建了一个程序,该程序可以从两本不同的书中获取用户输入,然后交换这两本书的信息。我这样做没有问题,但是出现了一个问题-当我按下 enter 时,书名将变成空白,并且在输出时,我当然会看到一个空白。 我的问题是,如何限制用户输入字母(A-Z,a-z)而不是空格?
输入到数组中的字符串,将它们保存在连续的内存地址中。我们也知道'NULL'在数组中表示为'\ 0'。
考虑到上述情况,我进行了多次测试,其中所有全部均未产生理想的结果。
下面是我所做的一些尝试。
第一次尝试
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
第二次尝试
while (strcmp(pBook1->name, ""))
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
另外,将以下代码视为程序的源代码:
#include <stdio.h>
#include <string.h>
#define MAX 50
struct Books
{
char name[MAX];
int ID;
float price;
};
void swap(struct Books *, struct Books *);
void main()
{
struct Books Book1, Book2, *pBook1, *pBook2;
pBook1 = &Book1;
pBook2 = &Book2;
// Input for the 1st book
printf("\n 1st Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook1->name, MAX, stdin);
while (pBook1->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook1->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook1->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook1->price);
// Input for the 2nd book
printf("\n 2nd Book \n ------------------------------");
printf("\n Enter the name: ");
fgets(pBook2->name, MAX, stdin);
while (pBook2->name[0] == '\0')
{
printf("\n Please enter a valid book name: ");
fgets(pBook2->name, MAX, stdin);
}
printf("\n Enter the ID: ");
scanf("%d", &pBook2->ID);
printf("\n Enter the price: ");
scanf("%f", &pBook2->price);
printf("\n Let's swap the info of the two books...");
swap(pBook1, pBook2);
printf("\n The info of the two books is now:");
printf("\n------------------------------ \n 1st Book \n ------------------------------------");
printf("\n Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook1->name, pBook1->ID, pBook1->price);
printf("\n------------------------------ \n 2nd Book \n ------------------------------------");
printf("Name \t\t ID \t Price \n %s \t\t %d \t %f", pBook2->name, pBook2->ID, pBook2->price);
}
void swap(struct Books *pB1, struct Books *pB2)
{
char temp[MAX];
strcpy(temp, pB1->name);
strcpy(pB1->name, pB2->name);
strcpy(pB2->name, temp);
int tempID = pB1->ID, tempPrice = pB1->price;
pB1->ID = pB2->ID;
pB2->ID = tempID;
pB1->price = pB2->price;
pB2->price = tempPrice;
}
答案 0 :(得分:1)
fgets
读取,直到遇到EOF
,\n
或N-1
个字节为止。因此,如果程序的用户按Enter键,它将读取\n
并停止。这意味着pBook1->name[0] == '\n'
。这就是为什么您与""
的相等性检查失败以及为什么pBook1->name[0] == '\0'
失败的原因。
请参阅此example。
这意味着如果用户输入了\n
,则需要检查\0
和Ctrl-D
,这是在* nix系统上输入EOF
的方式。
答案 1 :(得分:0)
当您按Enter键时,pBook1->name[0]
将变为\n
。您可以将某些功能用作strlen
,以确保名称中包含某些内容。