whatever
whatever

Reputation: 11

read and store the C string value

The instruction wanted me to read and store the C string value the user enters into the appropriate Name member.

Code

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};



struct Name coolname={{0}};

printf("Please enter the contact's first name: ");
scanf("%31s[^\n]", coolname.firstName); 

Two questions:

Upvotes: 0

Views: 66

Answers (1)

chux
chux

Reputation: 153338

's' not needed: scanf("%31s[^\n]", coolname.firstName); attempts to read input without spaces up to 31 characters and then read a [, ^, any white spaces, ].

Certainly a no-'s' is one step better: scanf("%31[^\n]"... as that will attempt to read up to 31 non-'\n' chracters.

Yet this will not consume the trailing '\n'.


Recommend to read all user input with fgets(). Perhaps as a helper function.

int read_line(const char *prompt, char *dest, size_t n) {
  fputs(prompt, stdout);
  fflush(stdout);

  dest[0] = '\0';
  char buf[n*2 + 2];
  if (fgets(buf, sizeof buf, stdin) == NULL) return EOF;

  size_t len = strlen(buf);
  if (len > 0 && buf[len - 1] == '\n') { // lop off potential \n
    buf[--len] = '\0';  
  }

  if (len >= n) { //  maybe add a `len == 0` test
    return 0; // indicate invalid input, 
  }

  strcpy(dest, buf);
  return 1; 
}

Now use the helper function

if (read_line("Please enter the contact's first name: ", coolname.firstName, sizeof coolname.firstName) == 1) {
  // Oh happy day, got first name
}
if (read_line("Please enter the contact's middle name: ", coolname.middleInitial, sizeof coolname.middleInitial) != 1)) {
  // Oh happy day, got middle name
}
if (read_line("Please enter the contact's last name: ", coolname.lastName, sizeof coolname.lastName) != 1)) {
  // Oh happy day, got last name
}

Upvotes: 1

Related Questions