How to parse a string in C (sscanf)

Поделиться
HTML-код
  • Опубликовано: 6 ноя 2024

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

  • @uzairbukhari99
    @uzairbukhari99 4 года назад +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 4 года назад +8

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

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

    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.

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

    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  Год назад

      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

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

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

  • @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

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

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

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

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

  • @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.

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

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

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

    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.

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

    All three examples neatly explained.

  • @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.

  • @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

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

    thanks for all your videos helping people to code in c

  • @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)

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

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

  • @kevin_math
    @kevin_math 2 месяца назад

    You re so great, love from Argentina❤

  • @purrfectempire
    @purrfectempire 5 лет назад +7

    Thanks a lot. that was helpful.

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

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

    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  2 года назад

      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

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

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

  • @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

  • @ДанилаФедоренко-ч6р

    THANK YOU MY MAN YOU ARE THE BEST !

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

    Thank you so much!! Very clearly explained!

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

    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  Год назад

      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 Год назад

      @@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  Год назад

      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 Год назад

      @@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.

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

    You're an Angel, thank you so much!

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

    step by step explanation, thank 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);
      //////////////////

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

    great video on this topic

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

    thank you very much you are a life saver dude

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

    Love your channel

  • @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

  • @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

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

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

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

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

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

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

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

    Thank you for this nice tutorial

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

    What about parsing through multiple lines?

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

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

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

    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  4 года назад +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.

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

    Good explanation, thank you :)

  • @ceo-s
    @ceo-s Год назад

    Very helpful. Thanks

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

    Thank you. It was really helpful

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

    So helpful mate

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

    good explanation, thank you very much!

  • @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.

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

    Thank u so much , now i understand :)

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

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

  • @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

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

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

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

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

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

    Thanks,u helped me a lot❤️❤️

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

    Thank! It was useful!

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

    Thanks!! 🤗

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

    Thank you my man

  • @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

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

    how to get multiple string inputs in c

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

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

  • @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?

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

    wow, thank you!

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

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

  • @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

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

    Thanks dude

  • @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!

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

    Thanks!!!

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

    Woow!

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

    thanks

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

    Great

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

    tremendous

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

    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  4 года назад

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

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

    so smart

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

    %[^;] awesome. Great tip!

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

    I didn't get anything 😪

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

    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

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

    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

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

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

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

      Thanks! What would you call it then? Deserializing?

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

      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  4 года назад

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

    • @CodeVault
      @CodeVault  4 года назад +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 4 года назад

      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.

  • @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