96r 96r - 17 days ago 7
C Question

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:

  • Id: An integer between 1 and 10000

  • Name and surname: at most 50 char including English letters and digits and space. Some people might have middle names. Name and surname ends with a semicolon.

  • Points: An integer less than 10000

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


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.