96r
96r

Reputation: 43

How do I scan a string up to when a certain character appears?

hi so this is what i have to do:

Every line has:

My problem is than i cant scan the string after the first integer because it includes spaces and has to stop scanning the string when a semicolon appears. can anybody help me figure this out??

A sample input would be:

5     //number of people

1 Maria Angel Juaves; 200    // Id nr, name , points

12 John Pick; 300

123 Dean Patrick Jr.; 230

5 Dea Torres; 140

11 Mick Doger; 250

Im am very new to programming also :D. Thank you in advance for anyone who answers

Upvotes: 2

Views: 11782

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

scanf allows you to read all characters up to a specific character(s) by using this format specifier:

%[^;,#]

This means "read a string of characters until you hit a semicolon, a comma, or an octothorpe (pound)". The ^ character at the beginning of the range means that the characters need to be excluded.

When you read into a fixed-size buffer, add the max number of characters to your format string:

char name[100];
int id, points;
int count = scanf("%d %99[^;];%d", &id, name, &points);
if (count == 3) {
    // the read was successful
}

99 above means the max number of characters that can fit into the name buffer. Note that the buffer must have an additional char for the null terminator.

Upvotes: 12

Related Questions