I want to scanf input like: "John, Surname, 9999" and commas should not be assigned to the scanned variable; spaces at the end and start of input deleted... Now to structure student_t in a shape of p->name, would be assigned "John," with this comma, instead of "John". How to do it in a way that the user inserts comma like in input example, but it's not assigned to p->name? I don't even know how to encloth with words my point. I'm hammering my head with this for about 50 hours now.
struct student_t
{
char name[20];
char surname[40];
int index;
};
struct student_t* read(struct student_t* p, int *err_code)
{
*err_code=0;
printf("Please enter data in a format: '[Name], [Surname], [index]':\n");
int c=scanf("%s, %s, %i", &p->name, &p->surname, &p->index);
return p;
}
void show(const struct student_t* p)
{
printf("%s %s, %i\n", p->name, p->surname, p->index);
}
example input:
Name, Surname, 9999
output to this example:
Name Surname, 9999
instead, my output is something like:
Name, , 0
so first "comma" typed by the user is assigned to p->name, and whitespace is p->surname, second comma is probably p->index which is of 'int' type, maybe that's why it's 0. If I do:
char comma1, comma2, space1, space2;
int c=scanf("%c%s%c%s%c%i%c", &space1, &p->name, &comma1, &p->surname, &comma2, &p->index, &space2);
output is:
ame, Surname,, 9999
edit1:
I thank everyone from the bottom of my heart. Now, I didn't mention that I also want to handle errors, though it might cast more light whether approach to decide.
*err_code=
0 -- everything is loaded to the structure properly
1 -- something went wrong, eg. user did not use commas when typing in format:'[Name], [Surname], [index]'
2 -- only name loaded properly
3 -- name and surname loaded properly (index went wrong)
Given that, I think that handling these errors using scanf would be quite problematic.
In the topic I used "how to scanf" because I don't know how to properly express scanning data from user to structure.
Now, following Stephan Lechner's wisdom, I attend this approach in a way:
char buffer[1024], *pch1, *pch2;
if (fgets(buffer,1024, stdin))
{
pch1=strchr(buffer, ',');
pch2=strrchr(buffer, ',');
if (pch1!=pch2 && pch1!=NULL)
{
char *name = strtok(buffer,","); // returns pointer to the beginning of the token
if (name) { //the place where "," is occured becomes a "NULL" character
sscanf(name," %19s", p->name); // skip leading spaces
char *surname = strtok(NULL,",");
if (surname) {
sscanf(surname," %39s", p->surname); // skip leading spaces
char *index = strtok(NULL,",");
if (index) {
p->index = (int)strtol(index, NULL, 10);
} //else *err_code=3;
} //else *err_code=2;
}
} else *err_code=1;
}