c - 我想在 c 中实现一个结构。在 FOR LOOP 部分,没有通过 scanf 获取 P[0].processname 它继续下一部分

标签 c structure

<分区>

我的代码是

//header files

#include <stdio.h>
#include<conio.h>

//declare structure for process

struct process
{
    char pr;                //process name
    int A,ex,end,period;   
};

struct process P[10];
int main()
{
    int N,i;//no. of process
    printf("enter number of task \n");
    scanf("%d",&N);
    printf(" enter processname executiontime period ");

    for(i=0;i<N;i++) 
    { 
    printf("\n  P[%d] . process name=",i);
    scanf("%c", &P[i].pr);
    printf("\n  P[%d] . execution time =",i);
    scanf("%d", &P[i].ex);
    printf("\n  P[%d] . period=",i);
    scanf("%d", &P[i].period);
    P[i].A=0;
    P[i].end = P[i].A + P[i].ex;    //here A=0
}
printf("processname\texecutiontime\tperiod\n");
for(i=0;i<N;i++) 
{
    printf("%c\t%d\t%d\n", P[i].pr,P[i].ex,P[i].period);
}
getch();

我得到的输出是:

enter number of task
3
 enter processname executiontime period

  P[0] . process name=
  P[0] . execution time =1
  P[0] . period=2
  P[1] . process name=
  P[1] . execution time =3
  P[1] . period=4
  P[2] . process name=
  P[2] . execution time =5
  P[2] . period=6

processname     executiontime   period
    1       2
    3       4
    5       6

发生了什么——为什么它不等待进程名称?

最佳答案

这是输入缓冲区问题。 一个简单的解决方案是在获取进程名称之前清除缓冲区。一种简单的方法是像这样编写 scanf():

scanf(" %c", &P[i].pr);

这里我在"%c"前写了一个空格;它会解决你的问题。 或者使用 getchar()fflush(stdin)int c; while ((c = getchar()) != EOF && c != '\n'); — 这些是对此的简单解决方案。 检查此代码;它会帮助你,

#include <stdio.h>
//declare structure for process
struct process
{
        char pr;                //process name
        int A,ex,end,period;
};

struct process P[10];
int main()
{
        int N,i;//no. of process
        printf("enter number of task \n");
        scanf("%d",&N);
        printf(" enter processname executiontime period ");

        for(i=0;i<N;i++)
        {
                printf("\n  P[%d] . process name=",i);
                scanf(" %c", &P[i].pr);
                printf("\n  P[%d] . execution time =",i);
                scanf("%d", &P[i].ex);
                printf("\n  P[%d] . period=",i);
                scanf("%d", &P[i].period);
                P[i].A=0;
                P[i].end = P[i].A + P[i].ex;    //here A=0
        }
        printf("processname\texecutiontime\tperiod\n");
        for(i=0;i<N;i++)
        {
                printf("%c\t%d\t%d\n", P[i].pr,P[i].ex,P[i].period);
        }
}

关于c - 我想在 c 中实现一个结构。在 FOR LOOP 部分,没有通过 scanf 获取 P[0].processname 它继续下一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712709/

相关文章:

c++ - 函数参数推送顺序

c++ - system() 调用...打开 mybatchfiles.bat

C++ 子结构

c - 在结构内部设置 typedef

C# 多线程应用程序 - 结构?

c - 从另一个应用程序访问(读/写)虚拟内存进程

c - 为什么我的内核没有超过共享内存限制?

C 链表实现

c - 程序终止后变量保留值,如何防止? C

c - 链表奇怪的行为