How to parse a string in C (sscanf)

Поделиться
HTML-код
  • Опубликовано: 1 июн 2019
  • Parsing a string in C is very simple using the scanf family of functions provided by the standard library.
    Check out our Discord server: / discord

Комментарии • 121

  • @uzairbukhari99
    @uzairbukhari99 3 года назад +6

    I have removed variable names, didn't want to spam the comment section.
    I'm using double instead of float, because of random value after decimal point.
    //String with "Uzair Bukhari" to separate with space inbetween. Use %[a-zA-Z ]
    //Incase of Uzair only, %[^,],%c
    //Parse Uzair Bukhari from W with + inbetween. Use %[a-zA-Z ]+%c instead of %[a-zA-Z ],%c
    /*
    #include
    #include
    int main()
    {
    char arr[] = "$GPGGA,181908.00,3404.7041778,N,Uzair Bukhari+W,4,13,1.00,495.144,M,29.200,M,0.10,0000*40";
    sscanf(arr,"%[^,],%f,%lf,%c,%[a-zA-z ]+%c,%u,%u,%lf,%lf,%c,%lf,%c,%lf,%s",name,&data1,&data2,&dir1,name3,&dir2,&data4,&data5,&data6,&data7,&dir3,&data8,&dir4,&data9,name2);
    printf("%s
    %f
    %lf
    %c
    %s
    %c
    %u
    %u
    %lf
    %lf
    %c
    %lf
    %c
    %lf
    %s",name,data1,data2,dir1,name3,dir2,data4,data5,data6,data7,dir3,data8,dir4,data9,name2);
    return 0;
    }

  • @rogercushman5097
    @rogercushman5097 3 года назад +7

    This was very helpful. Thank you for making this video. It is nice to see solid tutorials on C Programming. Well done.

  • @lightspd714
    @lightspd714 3 года назад +2

    This is the best channel for learning C. Thank you very much for the wonderful content!

  • @kurchak
    @kurchak 2 года назад +5

    This is exACTLy what I was looking for, thank you!

  • @ticklemecolor
    @ticklemecolor 2 года назад +1

    Thank you! This was a great tutorial. I was so confused until I found your channel. Solid content!

  • @uzairbukhari99
    @uzairbukhari99 3 года назад

    Thank you very much. I had problem parsing a lengthy and complex string but now I've got it working. Thank you and keep up the great work. I'll post a lengthy code here without variables on how to split a complex string, just incase someone needs help.

  • @fernandoalbuquerque6645
    @fernandoalbuquerque6645 3 года назад

    I'm impressing. I was looking for a better explanation about sscanf and this video has been perfect. Again.
    Tks so much.

  • @SamuelTGSamo3000
    @SamuelTGSamo3000 Год назад

    I'm studying Computer Science. Congratulations, you are the first video that saved my code on the career. I'll always remember you

  • @yassinemakhlouf9907
    @yassinemakhlouf9907 Год назад

    dude i've been searching for this so desperately.
    thank you so much.

  • @noahpeterson8513
    @noahpeterson8513 11 месяцев назад

    This is incredibly useful. I never knew you could use regex that easily in C. This has been a huge help in my work. Thank you!

    • @CodeVault
      @CodeVault  11 месяцев назад

      It's not quite full regex, but it is useful. I will make a video about using regex (with the help of a library) in C

  • @suponjubobu5536
    @suponjubobu5536 2 года назад

    THANK YOU SO MUCH! I spent so much time not knowing format specifiers such as %[^,] existed and being confused why scanf functions weren't working for stuff like CSV files.

  • @fransaucisse9816
    @fransaucisse9816 3 года назад

    Thank you so much !! I had much trouble to understand how to use it and your video really helped me !

  • @irfanakturk980
    @irfanakturk980 Год назад

  • @zeitreisender2023
    @zeitreisender2023 9 месяцев назад

    Awesome tutorial, my friend! High quality content. Thank you!

  • @joaum2009
    @joaum2009 6 месяцев назад

    thanks for all your videos helping people to code in c

  • @Hevletica
    @Hevletica 2 года назад

    All three examples neatly explained.

  • @Dablid77
    @Dablid77 3 года назад +1

    You're an Angel, thank you so much!

  • @purrfectempire
    @purrfectempire 4 года назад +7

    Thanks a lot. that was helpful.

  • @lkatt7
    @lkatt7 5 месяцев назад

    Thank you so much!! Very clearly explained!

  • @ogek7417
    @ogek7417 3 года назад

    step by step explanation, thank you!

  • @alejosuarez6657
    @alejosuarez6657 3 года назад +2

    I've a test today and u saved me, bc my program didn't work until now

  • @user-lo8mx2fj2c
    @user-lo8mx2fj2c Год назад

    THANK YOU MY MAN YOU ARE THE BEST !

  • @XM7D_Abasset
    @XM7D_Abasset Год назад

    Love your channel

  • @morty_dk
    @morty_dk 3 года назад

    Soooo good at explaining this! Thanks!!!!! 😁👌

  • @johanliebert8637
    @johanliebert8637 2 года назад

    So helpful mate

  • @batuhanlel9
    @batuhanlel9 3 года назад

    Thank you. It was really helpful

  • @bushraw66
    @bushraw66 2 года назад

    thank you very much you are a life saver dude

  • @niranjankumaryadav9098
    @niranjankumaryadav9098 3 года назад

    great video on this topic

  • @otnielewu7777
    @otnielewu7777 2 года назад

    Thank you for this nice tutorial

  • @peterhans8788
    @peterhans8788 2 года назад

    Good explanation, thank you :)

  • @Marki02
    @Marki02 2 года назад

    good explanation, thank you very much!

  • @danteeep
    @danteeep 3 года назад +1

    to save you up some time strings dont require the "&" in front of them (address) in case you didnt notice. also, if you dont put the ";" in the middle its fine as well. Thanks a lot for the video.

  • @indumathi9523
    @indumathi9523 3 года назад

    Thanks,u helped me a lot❤️❤️

  • @ceo-s
    @ceo-s 7 месяцев назад

    Very helpful. Thanks

  • @JussiHemlund
    @JussiHemlund Год назад

    This was useful. Thx

  • @zanden69
    @zanden69 2 года назад

    Thank u so much , now i understand :)

  • @Argletrough
    @Argletrough 3 года назад +1

    Thanks! Very helpful.
    I was thinking of writing a text parser with strtok_r but this seems like a much better idea.

  • @mykolazhabko3228
    @mykolazhabko3228 3 года назад

    Thank! It was useful!

  • @jacoblamberson3751
    @jacoblamberson3751 3 года назад

    Thank you my man

  • @alexbravo7467
    @alexbravo7467 3 года назад

    yes, yes, very useful .. thanking you .. :)

  • @sezerberber4625
    @sezerberber4625 2 года назад

    OMG. Finally i found that fuckin info. Thank u so much M8. God bless you

    • @sezerberber4625
      @sezerberber4625 2 года назад

      i cant split char.
      how can i split that?
      My file Kisiler.txt's datas =
      Kim Dibbert#64012.72#0.35#6
      /////////
      FILE* ptr;
      struct KISI Kisiler[999];
      char ch;
      ptr = fopen("Kisiler.txt", "r");char ch;
      do {
      ch = fgetc(ptr);

      printf("%c", ch);
      sscanf(ch,"%[^#]#%f#%f#%d",kisiler[count].isim,&Kisiler[count].para,&kisiler[count].oran,&kisiler[count].sansliSayi);

      count++;
      } while (ch != EOF);
      //////////////////

  • @yelimsnusm7551
    @yelimsnusm7551 2 года назад

    Thanks!! 🤗

  • @viettrinh8429
    @viettrinh8429 Год назад

    wow, thank you!

  • @mohammadhosseinzolfagharna8106

    Thanks dude

  • @adriaestevambeltran3395
    @adriaestevambeltran3395 3 года назад

    Thanks!!!

  • @mrDjuroman
    @mrDjuroman 4 года назад +3

    Thank you for this, it was useful!
    I have a question, my professor mentioned some %n in sscanf, what exactly is it, and can I use it to parse a string?

    • @CodeVault
      @CodeVault  4 года назад +7

      %n is a bit of a strange one, instead of printing or reading it actually saves the number of characters printed or read up until that point.
      int x;
      printf("test%n", &x);
      Would just save the number 4 in the integer x, because 4 characters were printed there.
      I may make a video on this as it's a much more different behaviour than the rest. Thanks for asking and I hope this helped!

    • @mrDjuroman
      @mrDjuroman 4 года назад

      @@CodeVault Thank you, that helped

  • @MrAvalosjl
    @MrAvalosjl Год назад

    What if I'm just interested in the character of the second column ("New York")?, do I have to read also the first and the last two columns? or there's a way I can only read the second one, kind of:
    sscanf(str, " [ ignore 1st string] %s , [ignore the last] ", city)
    printf("I just wanna show the %s, and don't wanna use more variables", city )

    • @CodeVault
      @CodeVault  Год назад

      If you know the character from which the second column appears in the string you can simply do:
      sscanf(str + 7, "%[A-Za-z ]", city); // read from character 7 and only read letters or spaces. Stops at comma basically.
      Although, if you don't know when that second column occurs you'd have to use the method shown in the video. You could improve it by simply using one variable for all the columns you don't care about.
      This issue is more or less the reason why database came into existence. Files (and strings) are not good for getting specific data out of them like you want here

  • @eva42sh
    @eva42sh 2 года назад

    thank you sir..it is helpful. if you make little the corner video, or remove the background, it will be much helpful :))))

    • @CodeVault
      @CodeVault  2 года назад +1

      Yea, I try to not let the webcam obscure the code, I remove it or make it smaller when it does. May get some recording equipment to remove the background at some point

  • @louaykhammar7268
    @louaykhammar7268 3 года назад

    thanks

  • @loubeauchesne8771
    @loubeauchesne8771 Год назад

    if the string is seperated using commas not semi colons can you do the same thing? do you need backslashes before each comma?

    • @CodeVault
      @CodeVault  Год назад +1

      No you don't backslashes. It should work if you simply replace the semi colons

  • @fuffi8550
    @fuffi8550 2 года назад +1

    I have soon a class test where I read from csv file some things and put them in memory to do something with them, our teacher taught us to use fgets to get the string, removing the
    if present and then slice it with strtok and putting the things in a struct using atoi/f for numbers and strcpy forstrings, why didn't they teach this to us? What's the problem that sscanf/fscanf have?
    Also they taught us to use fflush(stdin) so the crumbs get cleaned so i don't know why i should not use this instead of strtok and fgets

    • @CodeVault
      @CodeVault  2 года назад +1

      fgets is a bit more flexible, you can read any type of string and it will be parsed properly (although manually by you). sscanf (and fscanf) works only if the string you parsed you know it's 100% the format you provided, otherwise it could result in some weird behavior (for example, some floating point numbers have a , instead of a . while , is also your delimiter)

  • @Jose_T131
    @Jose_T131 Год назад

    Great

  • @ronjeremy1232
    @ronjeremy1232 4 года назад

    tremendous

  • @VinyZikss
    @VinyZikss Год назад

    How would you use specifiers when you have an N number of inputs
    Like let's say the string is "A B B C E ...... "with N chars , you cant really use "%c %c %c" because you dont know the number of characters. Is there a way to use this pattern matching in an scanf like "read %c N times and store it in an array". I dont know if that made sense.

    • @CodeVault
      @CodeVault  Год назад

      No, there isn't. You can simply call scanf multiple times in a loop though

  • @stu6097
    @stu6097 2 года назад

    I wish you talked about the part next to "int main"

    • @CodeVault
      @CodeVault  2 года назад

      There's this video you can look into: code-vault.net/lesson/a6g0gtgb4x:1603733522711

  • @AbhishekSingh-qt4uq
    @AbhishekSingh-qt4uq 3 года назад

    Sir why are u using ; after the format specifier cant we use space instead of it or does it has some special meaning here

    • @CodeVault
      @CodeVault  3 года назад +1

      It's just a convention of mine. Feel free to use spaces instead. I avoid using them simply because you might want to have strings with actual spaces in the parsed string.

  • @EchoENKO
    @EchoENKO Год назад

    so smart

  • @sarker_sudi21
    @sarker_sudi21 9 месяцев назад

    Thank you for the explanation. Quick question, why did u use the semicolon in the format code. "%[a-zA-z ]; %[a-zA-Z ]; ........ ?

    • @CodeVault
      @CodeVault  9 месяцев назад

      I picked it as a separator. No real reason behind the semicolon specifically, you can use any character you want. It's just important that the separator character won't be found in the input text itself

    • @sarker_sudi21
      @sarker_sudi21 9 месяцев назад

      @@CodeVault but since we are using [a-zA-Z] which means we only read alphabets, doesn't it imply that we will be ignoring the semicolon (our separator) here?

    • @CodeVault
      @CodeVault  9 месяцев назад

      It's related to the input string, not the format itself. Let's say we change the separator to a space character. And we change the semicolons to space in the input text, like so: "Andrew New York 20 0". With this setup, you will notice that "New" and "York" will be considered two different fields even though it's the name of the city. That's why the space character as a separator is not a good solution

    • @sarker_sudi21
      @sarker_sudi21 9 месяцев назад

      @@CodeVault Makes sense. Another question, if a string has a space as a separator, then do I need to put the space between the formats as well like you out the semicolon between the formats to imply that it is a separator? Because I tried it without putting any space in between the formats and it still works which doesn't make sense.
      the code:
      char line[] = "This is a line";
      sscanf(line2, "%s %s", line, word);
      printf("%s
      %s
      ", line, word);
      and if I write this instead:
      sscanf(line2, "%s%s", line, word); // with no space
      they both give the same correct output i.e. they both ignore the space separator.

  • @erilshackle
    @erilshackle 2 года назад

    Woow!

  • @lilcameauxx
    @lilcameauxx Год назад

    What about parsing through multiple lines?

    • @CodeVault
      @CodeVault  Год назад

      You could add
      to the format string and parse the next line

  • @parshangiahi4737
    @parshangiahi4737 3 года назад

    what happens if you have multiple lines in a file? how do you read that?

    • @CodeVault
      @CodeVault  3 года назад

      You can use fgets to get each line then pass it to sscanf like I do in the video. Here's the lesson related to this: code-vault.net/lesson/yxllgxvfmb:1603733521595
      Or just use fscanf

  • @harshkhare3519
    @harshkhare3519 4 года назад

    Hey, I have few commands in cmd file, and I have to parse them all before using them individually in my c program. HOw to do it?

    • @CodeVault
      @CodeVault  4 года назад +1

      You can make use of fgets to read line by line then... it depends if the lines are complex or not. You might have to use regex to parse them properly.

    • @harshkhare3519
      @harshkhare3519 4 года назад

      @@CodeVault I'll surely try it. Thank you so much, you are great man

  • @michaelpatterson1096
    @michaelpatterson1096 Год назад

    %[^;] awesome. Great tip!

  • @drunkbout9694
    @drunkbout9694 2 года назад

    hello , please I don't see the degree on the output

    • @CodeVault
      @CodeVault  2 года назад

      How are you printing that to the console?

  • @FS_03
    @FS_03 2 года назад

    I can’t use “sscanf” in Visual Studio 2019. What code should I replace?

    • @CodeVault
      @CodeVault  2 года назад +1

      Just add this line at the beginning of your main file:
      #define _CRT_SECURE_NO_WARNINGS

    • @FS_03
      @FS_03 2 года назад

      @@CodeVault thank you. Btw I have submitted my Assignment by using the main as you show

  • @Revanth-jl8uv
    @Revanth-jl8uv 2 года назад

    how to get multiple string inputs in c

    • @CodeVault
      @CodeVault  2 года назад

      Just use fgets if you want to read a line of text

  • @71GA
    @71GA 4 года назад

    Why do you write "char name[20] = { 0 };" Why is the value in the curly braces?

    • @CodeVault
      @CodeVault  4 года назад +1

      With curly braces you can initialize any array. Something like:
      int arr[3] = { 1, 2, 3 };
      Would create an array of 3 elements with the values 1, 2 and 3.
      char name[20] = { 0 };
      Creates an array of 20 chars and initializes all the elements to 0.
      Technically this notation only initializes the first value to 0 but, because I'm not specifying a value for all the other 19 elements they default to 0 as well.
      If you'd write instead:
      char name[20] = { 'a' };
      It would set the first char to 'a' and the rest to 0.
      Hope this is clear enough!

  • @potatoesweet4890
    @potatoesweet4890 3 года назад

    what if the string is Andrew;;New york;20;0?
    how do you parse the ;; so that it stores a blank when printed?

    • @CodeVault
      @CodeVault  3 года назад

      The sscanf function already does that... although, it cannot validate the string for you, so if you have too many ';' then it will break.

    • @potatoesweet4890
      @potatoesweet4890 3 года назад

      @@CodeVault what do you recommend to use?

    • @CodeVault
      @CodeVault  3 года назад

      You can manually parse it with strtok, I think

  • @voipims
    @voipims 3 года назад

    in the title of the video write like "how to parse a string in c using sscanf" , so when someone search sscanf your video come in the search ...becuase of title you are notr getting many views , even though your contents are good...

    • @CodeVault
      @CodeVault  3 года назад

      I applied your suggestions. Not sure how much they help as I did add those to tags. Thanks anyway!

  • @MrStefanokj
    @MrStefanokj 3 года назад

    Hi, what is the best way to parse a file like this: pastebin.com/s4LxFNGE
    To be able to insert each element into a dynamic vector of structures?
    This is the structure: pastebin.com/Yxd1G7PM

    • @CodeVault
      @CodeVault  3 года назад

      Probably with fgets and then parsing it locally with strtok or something

  • @vlxedits
    @vlxedits 3 года назад

    this is not parsing a string, this is a parsing a char.

    • @CodeVault
      @CodeVault  3 года назад

      No, it can parse multiple characters

    • @vlxedits
      @vlxedits 3 года назад

      @@CodeVault yeah but i wanted a string variable parser

  • @enmanuelgonzalezaguilera597
    @enmanuelgonzalezaguilera597 Год назад

    I didn't get anything 😪

  • @HenryTitor
    @HenryTitor 3 года назад

    It’s technically not parsing. But a good video nonetheless

    • @CodeVault
      @CodeVault  3 года назад

      Thanks! What would you call it then? Deserializing?

    • @HenryTitor
      @HenryTitor 3 года назад

      CodeVault The “[a-zA-Z]” is actually a Lexer, using Regex, which is not Parser. Though I once read somewhere that stdio.h doesn’t use but mimic Regex using Formating/Parsing.

    • @CodeVault
      @CodeVault  3 года назад

      Yeah, you don't have full regex support in the stdio.h library

    • @CodeVault
      @CodeVault  3 года назад +2

      I used the word "parsing" because it's more known, not necessarily correct. Gotta shape the titles/thumbnails of videos around what people mean when they are searching on RUclips and other platforms.

    • @HenryTitor
      @HenryTitor 3 года назад

      CodeVault It definitely worked! I got here by searching for a GNU roff parser library. Hahaha, such irony when programming tutorials also need to fight the algorithm. Nice tutorials btw.

  • @AbhishekSingh-lu8kt
    @AbhishekSingh-lu8kt 3 года назад

    sir please tell me what is wrong in this code output is wrong and i cant find out what is problem and sir please help me how to implement this (i want the name array to have full name including spaces)
    #include
    void main ()
    {
    char str[] = "Abhishek Singh;22;Delhi;124586";
    char name[20] = { 0 };
    int age;
    char city[10] = { 0 };
    int pincode;
    printf ("The name is %s age is %d city is %s pincode is %d", str);
    sscanf (str, "%[A-Za-z ]s %d %s %d", name, &age, city, &pincode); //i Want the name array to have spaces
    printf ("%s %d %s %d", name, age, city, pincode);
    printf ("hello %d", age);
    }
    thank you sir