What format should be used: scanf \ string, string, int, int /?

I have data in the following format \a,b,c,d/, where a, b are strings of letters and numbers; c, d are integers.

I tried using the format \%s,%s,%d,%d/to scan it, but it makes it a,b,c,d/be scanned in the first line instead of a.

Question:

Is there anything that I could print in a format to achieve the desired result?

+4
source share
3 answers

You can use the following format string to use commas as separators:

"\\%[^,],%[^,],%d,%d/"

The idea is to tell scanf to read something that is not a comma for each line, then read the separation comma and continue.

( !):

char a[100], b[100];
int c=0, d=0;

scanf("\\%[^','],%[^','],%d,%d/", a, b, &c, &d);
printf("%s, %s, %d, %d\n", a, b, c, d);

- . , , fgets, , sscanf, .

+4

fscanf (3).

-

char str1[80];
char str2[80];
memset (str1, 0, sizeof(str1));
memset (str2, 0, sizeof(str2));
int  n3 = 0, n4 = 0;
int pos = -1;
if (scanf ("\\ %79[A-Za-z0-9], %79[A-Za-z0-9], %d, %d /%n",
           str1, str2, &n3, &n4, &pos) >= 4
    && pos > 0) {
   // be happy with your input
 }
 else {
   // input failure
 }

, , , é ; , UTF-8, .

( ) ( scanf , , %d). , , , \AB3T, C54x, 234, 65/, getline (3) fgets (3) (, sscanf strtol...). , %d ! , . , %n (, !) scanf .

+2

:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char a[10010];

    gets(a);
    int l = strlen(a);

    char storded_first[10010], storded_second[10010];
    char for_int_c[10010], for_int_d[10010];
    int c,d;

    char first_symbol, last_symbol;
    int i;
    int cnt = 0;
    int j=0;

    for(i=0; i<l; i++)
    {
        if(a[i]=='\\')
            first_symbol = a[i];
        else if(a[i]=='/')
            last_symbol = a[i];

        else if(a[i]==',')
        {
            cnt++;
            j=0;
        }

        else if(cnt==0)
        {
            storded_first[j]=a[i];
            j++;
        }
        else if(cnt==1)
        {
            storded_second[j]=a[i];
            j++;
        }
        else if(cnt==2)
        {
            for_int_c[j]=a[i];
            j++;
        }
        else if(cnt==3)
        {
            for_int_d[j]=a[i];
            j++;
        }
    }

    c = atoi(for_int_c);
    d = atoi(for_int_d);


    printf("%c%s, %s, %d, %d%c\n",first_symbol, storded_first, storded_second, c, d, last_symbol);

    return 0;
}
-2

All Articles