简体   繁体   English

如何在 c 的一行中打印不同的 arrays?

[英]How to print different arrays in a single line in c?

I wanted to print all my array[i] in a single line in a new function, but everything gone misaligned in the table of my output.我想在新的 function 的一行中打印我所有的数组 [i],但我的 output 的表格中的所有内容都未对齐。
I can't find where the problem is:我找不到问题出在哪里:

#include <stdio.h>
#include <stdlib.h>
void userInput();
void formOutput(int, char (*)[50], char (*)[10], int *);

void main()
{
   userInput();
}

void userInput()
{   int totalSubj;

    printf("\nHow many subject to be registered: ");
    scanf("%d",&totalSubj);

    char subjCode[totalSubj][10], subjName[totalSubj][50];
    int subjCred[totalSubj];

    for(int i=0;i<totalSubj;i++)
    {
        printf("\nSUBJECT CODE %d.: ",i+1);
        scanf("%s",&subjCode[i]);

        printf("SUBJECT NAME: ");
        fgets(subjName[i],50,stdin);

        printf("SUBJECT CREDIT: ");
        scanf("%d",&subjCred[i]);
    }

    formOutput(totalSubj, subjName, subjCode, subjCred);
}

void formOutput(int subjTotal, char nameSub[][50], char codeSub[][10], int credSub[])
{
    printf("Subject Name                  Subject Code          Credit\n");
    printf("------------------------------------------------------------------");

    for(int i=0;i<subjTotal;i++)
    {
        printf("\n%s  ",nameSub[i]);
        printf("%s\t\t",codeSub[i]);
        printf("%d",credSub[i]);
    }
}

Here is the output.这是 output。
The values in the table are all messed up, some are also duplicated which is not what I wanted it to be:表中的值都搞砸了,有些也是重复的,这不是我想要的:

How many subject to be registered: 3

SUBJECT CODE 1.: DCS1053
SUBJECT NAME: Programming Technique
SUBJECT CREDIT: 3

SUBJECT CODE 2.: DCS1062
SUBJECT NAME: Current Issues in ICT
SUBJECT CREDIT: 3

SUBJECT CODE 3.: DCS1083
SUBJECT NAME: Object Oriented Programming
SUBJECT CREDIT: 3
Subject Name                  Subject Code          Credit
------------------------------------------------------------------
Programming Technique
  DCS1053               3
Current Issues in ICT
  DCS1062               3
Object Oriented Programming
  DCS1083               3
Process returned 3 (0x3)   execution time : 53.708 s
Press any key to continue.

I would like my output to look like this:我希望我的 output 看起来像这样:

Subject Name                Subject Code           Credit    
---------------------------------------------------------------  
Programming Technique       DCS1053                   3  
Current Issues in ICT       DCS1062                   3
Object Oriented Programming DCS1083                   3

you read the subject name using fgets so that one contains the newline and you print it => the subject is alone on its line, then on the next line you have the code and the credit您使用fgets读取主题名称,以便其中包含换行符并打印它=>主题单独在其行上,然后在下一行您有代码和信用

to read a string containing spaces except newline you can use scanf :要读取包含除换行符以外的空格的字符串,您可以使用scanf

scanf(" %49[^\n]", &subjName[i]);

the space at beginning of the format allows to remove spaces/newline/.. before the first non space character, that allows to bypass the newline enter after the code格式开头的空格允许在第一个非空格字符之前删除空格/换行符/..,这允许绕过代码后的换行符输入

to have your output as you expect you cannot write a fixed amount of space/tab, use the capacities of printf to write on a given width要让您的 output 像您期望的那样无法写入固定数量的空格/制表符,请使用printf的容量在给定宽度上写入

also it is not consistent to have a width to print smaller than the size of the fields you can read打印的宽度小于您可以读取的字段大小也是不一致的

The function fgets() takes the newline as an input and it inserts the newline char into the variable and you get disastrous output. function fgets()将换行符作为输入,并将换行符插入到变量中,你会得到灾难性的 output。

This code may help you to solve your problem (handy explains are added in comments):此代码可以帮助您解决问题(注释中添加了方便的解释):

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

// defining macros the maximum lengths of array as a constant    
#define SUB_NAME_MAX 50
#define SUB_CODE_MAX 10

// function signature
void formed_output(int, char [][SUB_NAME_MAX], char [][SUB_CODE_MAX], int[]);

int main(void) {
    int total;

    printf("How many subjects to be registered? ");
    scanf("%d", &total);

    char sub_code[total][SUB_CODE_MAX], sub_name[total][SUB_NAME_MAX];
    int sub_credit[total];

    for (int i = 0; i < total; i++) {
        printf("\nSUBJECT CODE %d.: ",i+1);
        scanf("%s", &sub_code[i]);

        printf("SUBJECT NAME: ");
        fseek(stdin, 0, SEEK_END); // to avoid skipping user input
        fgets(sub_name[i], SUB_NAME_MAX, stdin);

        char *pos;
        if ((pos=strchr(sub_name[i], '\n')) != NULL)
            *pos = '\0'; // this one is the trick which will help to
                         // remove newline of each 'sub_name' array

        printf("SUBJECT CREDIT: ");
        scanf("%d", &sub_credit[i]);
    }

    printf("\n"); // for good-looking purpose

    formed_output(total, sub_name, sub_code, sub_credit);

    return 0;
}

void formed_output(int total, char name[][SUB_NAME_MAX], char code[][SUB_CODE_MAX], int cred[]) {
    printf("Subject Name                       Subject Code          Credit\n");
    printf("---------------------------------------------------------------\n");

    for(int i = 0; i < total; i++) {
        printf("%-35s", name[i]); // left-justified for next 35 places
        printf("%-22s", code[i]); // left-justified for next 22 places
        printf("%d \n", cred[i]);
    }
}

Sample Output:样品 Output:

How many subjects to be registered? 3 

SUBJECT CODE 1.: DCS1053
SUBJECT NAME: Programming Technique    
SUBJECT CREDIT: 3

SUBJECT CODE 2.: DCS1062
SUBJECT NAME: Current Issues in ICT
SUBJECT CREDIT: 3

SUBJECT CODE 3.: DCS1083
SUBJECT NAME: Object Oriented Programming
SUBJECT CREDIT: 3
Subject Name                       Subject Code          Credit
---------------------------------------------------------------
Programming Technique              DCS1053               3
Current Issues in ICT              DCS1062               3
Object Oriented Programming        DCS1083               3

Try this code in formOutput()formOutput()中尝试此代码

 printf("Subject Name \t\t\tSubject Code\t\tCredit\n");
printf("-------------\t\t\t------------\t\t------\n");
int i=0;
for( i=0;i<subjTotal;i++)
{
    printf("\n%s\t\t\t",nameSub[i]);
    printf("%s\t\t",codeSub[i]);
    printf("%d\n",credSub[i]);
}

everything gone misaligned in the table of my output.我的 output 的表格中的所有内容都未对齐。

fgets() retains a '\n' it may have read. fgets()保留它可能已读取的'\n'
fgets() and scanf() do not play well together. fgets()scanf()不能很好地配合使用。


Avoid using both fgets() with scanf() .避免同时使用fgets()scanf() The first reads a line , the 2nd does not.第一个读取一行,第二个没有。

With line inputs, use fgets() .对于线路输入,使用fgets() Use width limitations when filling a character array.填充字符数组时使用宽度限制。

Using fgets() with sscanf() is OK.fgets()sscanf()一起使用是可以的。

void userInput() {
  char buf[100];
  int totalSubj;

  printf("\nHow many subject to be registered: ");
  fgets(buf, sizeof buf, stdin); 
  sscanf(buf, "%d", &total);

  char subjCode[totalSubj][10], subjName[totalSubj][50];
  int subjCred[totalSubj];

  for (int i=0; i<totalSubj; i++) {
    printf("\nSUBJECT CODE %d.: ",i+1);
    fgets(buf, sizeof buf, stdin); 
    sscanf(buf, "%9s", subjCode[i]);  // & not used when calling with an array

    printf("SUBJECT NAME: ");
    fgets(buf, sizeof buf, stdin); 
    sscanf(buf, "%49s", subjName[i]);

    printf("SUBJECT CREDIT: ");
    fgets(buf, sizeof buf, stdin); 
    sscanf(buf, "%d",&subjCred[i]);
  }

  formOutput(totalSubj, subjName, subjCode, subjCred);
}

Better code would also test the return values of fgets() and sscanf() to look for errors.更好的代码还会测试fgets()sscanf()的返回值以查找错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM