cstringscanf

Scanf with NameSurname into two separate strings


I have a string to be read that is AaaaBbbb and I want it to be assigned into two separate strings as Aaaa and Bbbb. In fact I have to read a SurnameName, with no spaces and have it in the two separate strings.

My goal is to separate the Surname to further process it. I have not to check for unexpected cases and there is nothing else to check, just a list of SurnameName.

I can't manage to do that in a "simple" way.

My best attempt was

char str1[20], str2[20], str3[20]; 
fscanf(hl_inp, "%1c%[^A-Z]%s", str1, str2, str3);

but I would like to avoid any reassembling process, here with str1 and str2.

Any idea to do that directly, or any better that my attempt?

EDIT: Complete reprashing, lets try a last time.

I have a string. It is all lower case chars with two and only two Upper case characters. The string can be 20 chars max.

The two upper case characters follow these rules:

This is best attempt:

char name[] = "WillisBruce";
    char str1[20], str2[20], str3[20];
    sscanf(name, "%1s%[^A-Z]%s", str1, str2, str3);

    strcat(str1, str2);

    printf("Name: %s, Surname: %s", str3, str1);

The string is "WillisBruce" in the example. But it could be "CareyMariah", "JonhElton" as well as "ObamaBarak".

It could be not "McDonaldDonald", according to the rules.

I have not to check for the rules, I can have them as granted.

My example did the job I want, but I would like to know if I can avoid any kind of reassembling.


Solution

  • Transferring a comment into an answer

    What about using:

    fscanf(hl_inp, "%1c%[^A-Z]%s", &str1[0], &str1[1], str3);
    

    This uses your first format string. It places the single character in str1[0] and the rest of the first name in str1[1] onwards, so there's no reassembly required.

    You should protect against buffer overflows too (see also How to prevent scanf() causing a buffer overflow in C?):

    fscanf(hl_inp, "%1c%18[^A-Z]%s", &str1[0], &str1[1], str3);
    

    You will run into problems with names like "McDonaldIain". However, such devious issues are probably beyond the scope of the exercise.