简体   繁体   中英

How to scan a string with white spaces in structure members in C?

struct Demo{
   char a[50];
   char b[50];
   int a;
};
  • Can anyone give the code for this structure Demo where a and b will contains string with different words[white-spaces].

    I tried

    • scanf("[^\\n]s",name.a); //where name is the object
    • fgets(name.a,50,stdin);

Note : we can't use gets method as well

So, If any other method is there, please provide me.

To read a line of user input into char a[50]; with its potential trailing '\\n' trimmed:

if (fgets(name.a, sizeof name.a, stdin)) {
  name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}

Work is needed to cope with consuming excessive long input lines and using the last element of name.a[] such as:

// Alternative
if (scanf("%49[^\n]", name.a) == 1) {
  // consume trailing input
  int ch;
  while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
    ;
  }
} else {  // Handle lines of only \n, end-of-file or input error
  name.a[0] = '\0';
}

The scanf("%49[^\\n]%*c", name.a) approach has trouble in 2 cases:
1) The input is only "\\n" , nothing is saved in name.a and '\\n' remains in stdin .
2) With input longer than 49 characters (aside from the '\\n' ), the %*c consumes an extra character, yet the rest of the long input line remains in stdin .
Both of these issues can be solves with additional code too.

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