Reputation: 95
I am trying to write some basic user input code where the I ask for first and last name in the form: first,lastname and I would then store each name into string variables first and last? The issue is, the user can add as many spaces before or after the comma, and there can also be a comma before the first name.
Ex. valid inputs: 'John,smith' ',>>John,>>Smith' ',John>>>,>>>smith'
The > are spaces, I think you get the idea.
I've been trying to use scanf() but definitely running into issues with it.
Would I have to just use getchar() and go character by character until '\n', and if they are not a ' ' or ',' then copy it to the respective variable?
#include <stdio.h>
#include <string.h>
int main()
{
char first[50], last[50];
printf("Enter first name, last name: ");
scanf("%s,%s", &first, &last);
printf("The name is %s %s.", first, last);
//input: john,smith -> the output would be "The name is john,smith ."
// (no 'last' stored) I'm not sure why?
return 0;
}
Upvotes: 0
Views: 581
Reputation: 36611
A simple implementation using strchr
to find a ','
in line
and change it to a null terminator, then using strncpy
to copy into each of first
and last
.
#include <string.h>
#include <stdio.h>
#define LINE_SIZE 256
#define NAME_SIZE 128
int main(void) {
char line[LINE_SIZE];
char first[NAME_SIZE], last[NAME_SIZE];
fgets(line, LINE_SIZE, stdin);
char *tok;
if ((tok = strchr(line, ',')) != NULL) {
*tok = '\0';
strncpy(first, line, NAME_SIZE-1);
strncpy(last, tok + 1, NAME_SIZE-1);
printf("%s, %s\n", first, last);
}
else {
printf("Comma not found.\n");
}
return 0;
}
Upvotes: 1