简体   繁体   中英

multiple char arrays scanf in a single string of text in C

For an exercise in C, I need to put three names in three different arrays of char but the input of the three names is on a single line.

#include <stdio.h>

int main(){
    char a[3], b[3], c[3];

    scanf("%s%s%s", a, b, c);
    printf(" \n %s ", a);
    printf("%s ", b);
    printf("%s", c);

    return 0;
}

The input will be in a single line like this: "aaabbbccc"
(without " ").

I tried with that but it require to press enter three times.

Is there a way to scan more than one array with a single line of input?

I can only use stdio.h and scanf.

edit:

This is the full exercise translated (the original one was in italian).

Copy those declaration at the top of your code.

struct person {
    char name[10];
    struct person * mother;
    struct person * father;
} ;
typedef struct person Person;

write a code that declares three Person type variables and reads from input:

The son's name (composed by 10 characters, add the special character $ if needed).

The mother's name (same as the son's).

The fater's name (same as the son's).

(use NULL constant if father and mother are unknown).

This will represent a family of 3 people. Then write a void function that prints a Person's mother and father s' name. If those names are unknown then print "Unknown" (check that the pointer is different from NULL).

Call this function on the whole family members.

This is the input exemple:

Roberta$$$Anna$$$$$$Massimo$$$

Ignoring the last part of the exercise, my problem is that the input is made by 30 characters, and the name array length is 10. I obviously can't edit name array's length.

edit: I tried with the "%3s" solution on the three lenght arrays and or seems ti work fine, but, if there is a '\\0' character on the 3rd slot of the array, this shouldn't be anche issue?

Hey Snoopy3 Stack overflow is not a platform to get your home works done. Here I can only help you by modifying your code.

You can have multiple char arrays scanf() in a single string of text in C using format specifier in scanf() .

Try this code :-

#include <stdio.h>

int main()
{
  char a[10], b[10], c[10];

  scanf("%10s%10s%10s", a, b, c);   // total 30 chars 10 per each string.

  for (int i = 0; i < 10; i++)      // removing rest '$';
  {
    if (a[i] == '$')
    {
      a[i] = '\0';
    }
    if (b[i] == '$')
    {
      b[i] = '\0';
    }
    if (c[i] == '$')
    {
      c[i] = '\0';
    }
  }

  printf(" \n %s ", a);
  printf("%s ", b);
  printf("%s", c);

  return 0;
}

Output :-

Roberta$$$Anna$$$$$$Massimo$$$

 Roberta Anna Massimo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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