首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用空格读取结构中的字符串?

如何用空格读取结构中的字符串?
EN

Stack Overflow用户
提问于 2017-08-07 12:17:17
回答 1查看 1.8K关注 0票数 0

我们的公司办公室要求一个应用程序,将维护所有注册大学在钦奈,该应用程序应该是用户友好的搜索一所大学。创建一个名为“University”的结构,其属性如下:名称、许可号和区号。

要求:一所大学的执照号码应为6位,前2位必须是大写字母,最后4位必须是号码。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct University
{
  char name[100];
  char license[10];
  int area;

}u[10];

void main()
{
  int i, n, r, k = 0, flag = 1, f2 = 1, j, search = 0;
  char s[100];
  printf("Enter the number of records\n");
  scanf("%d", &n);
  printf("Enter the details of %d universities\n", n);

  for (i = 0; i<n; i++)
  {
    printf("Name of the University\n");
    getchar();
    scanf("%s", u[i].name);
    j = strlen(u[i].name);
    if (j <= 1)
    {
      f2 = 0;
      break;
    }
    printf("License Number\n");

    scanf("%s", u[i].license);
    k = strlen(u[i].license);
    if (k<1)
    {
      f2 = 0;
      break;
    }

    if (k<6)
    {
      flag = 0;
    }
    else if ((u[i].license[0] >= 'A' && u[i].license[0] <= 'Z') && (u[i].license[1] >= 'A' && u[i].license[1] <= 'Z') && (u[i].license[2] >= '0' && u[i].license[2] <= '9') && (u[i].license[3] >= '0' && u[i].license[3] <= '9') && (u[i].license[4] >= '0' && u[i].license[4] <= '9') && (u[i].license[5] >= '0' && u[i].license[5] <= '9') && k == 6)
    {
      flag = 1;
    }
    else
    {
      flag = 0;
    }
    printf("Area Code\n");
    scanf("%d", &u[i].area);
    //printf("%d",u[i].area);
    if (u[i].area <= 0)
    {
      f2 = 0;
    }

  }
  if (flag == 0)
  {
    printf("Sorry! You have entered incorrect license number.");
  }
  else if (f2 == 0)
  {
    printf("Unable to continue");
  }
  else
  {
    printf("Enter the name of the University to be searched\n");
    scanf("%s", s);
    for (i = 0; i<n; i++)
    {
      if ((strcmp(u[i].name, s)) == 0)
      {
        search = 1;
      }
    }
    if (search == 1)
    {
      printf("University is licensed one.");
    }
    else
    {
      printf("University is not found.");
    }
  }
}

当我给出3的大学数时,它就不会为第三所大学接受输入。

测试用例

输入1

输入记录的数量

3.

输入3所大学的详细信息

大学名称

SRM

许可证号码

SR1234

区号

28

大学名称

马德拉斯大学

许可证号码

SP0904

区号

18

大学名称

巴拉斯大学

许可证号码

BU0101

区号

35

输入要搜索的大学名称

SRM

产出1

大学有执照。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-07 13:22:11

似乎你对只读包含空格的c-字符串感兴趣。要做到这一点,您可以使用fgets。这是一个玩具程序:

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

struct s {
    char name[100];
    int something;
};

int main(void)
{
    struct s myStruct;
    printf("%s", "Enter name: ");
    fgets(myStruct.name, 100, stdin);

    myStruct.name[strlen(myStruct.name) - 1] = '\0'; //This should remove the newline char at the end
    printf("Name is: %s", myStruct.name);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45546702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档