使用c和do-while循环在struct对象中存储值

时间:2010-11-19 19:29:45

标签: c

我正在尝试在struct对象中存储一些值,我想重复提示,直到用户键入“yes”。我想为此使用do-while循环。我已经失败了第一个“姓氏”的读入。当我输入内容时,程序就会停止(没有错误)。我甚至不使用do-while,因为我不确定它是否适用于我的while()条件。

#include <ctype.h>
#include <stdio.h>
#include <string.h>

struct employeelist 
{
 char last[6];
 char first[6];
 int pnumber;
 int salary;
};

int main()

{
 struct employeelist employee[5]; 
 char check; 

 //do
 //{
 printf("Hello. Please type in the last name, the first name, the personal number and the salary of your employees.\n");
 printf("Last name: ");
 scanf("%c", employee[1].last);  

 printf("First name: ");
 scanf("%c", employee[1].first);  

 printf("Personal number: ");
 scanf("%d", &employee[1].pnumber);  

 printf("Salary: ");
 scanf("%d", &employee[1].salary);  

 printf("You have more employess (yes/no)?: ");
 scanf("%c", &check);  
 //}while (scanf("yes"));

 return 0;
}

4 个答案:

答案 0 :(得分:2)

如果您正在尝试获取字符串,请使用%s作为格式说明符。您可能还希望将其长度限制为5,因为这是lastfirst的空间。那就是%5s。此外,5个字符对于名称来说非常短。

另一条评论:C中的数组从零开始,因此employee[1]是数组中的第二个employeelist。如果要在具有递增索引的循环中执行此操作,请从0开始。

答案 1 :(得分:1)

嗨,当你读取char数组时,你必须使用scanf(“%s”,employee [1] .last); %s但不是%c

答案 2 :(得分:1)

您认为此代码的作用是什么?

scanf("%c", ....

%c表示scanf只能读取 ONE 字符 一封信不会给你一个完整的名字。

您需要切换到%s作为初学者。

答案 3 :(得分:1)

  1. 首先是第一个工作的索引 将是'0',而不是1.
  2. 字符串的错误标识符,它 应该是%s。
  3. 如果你只是想迭代 问你/然后只是改变 显示从是/否到y / n的消息 而且也改变了那种奇怪的感觉 条件检查=='y'|| check =='Y'。
  4. 代码实际上不起作用 经过5次迭代后因为你 初始化只有5个结构 那种类型。你为什么不加入呢? 循环?