How to parse a string in C (sscanf)

แชร์
ฝัง
  • เผยแพร่เมื่อ 18 ก.ย. 2024
  • 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 4 ปีที่แล้ว +8

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

  • @kurchak
    @kurchak 3 ปีที่แล้ว +5

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

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

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

  • @ticklemecolor
    @ticklemecolor 2 ปีที่แล้ว +1

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

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

  • @alejosuarez6657
    @alejosuarez6657 3 ปีที่แล้ว +2

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

  • @purrfectempire
    @purrfectempire 4 ปีที่แล้ว +7

    Thanks a lot. that was helpful.

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

  • @Hevletica
    @Hevletica 2 ปีที่แล้ว

    All three examples neatly explained.

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

  • @joaum2009
    @joaum2009 9 หลายเดือนก่อน

    thanks for all your videos helping people to code in c

  • @irfanakturk980
    @irfanakturk980 ปีที่แล้ว

  • @kevin_math
    @kevin_math 22 วันที่ผ่านมา

    You re so great, love from Argentina❤

  • @niranjankumaryadav9098
    @niranjankumaryadav9098 4 ปีที่แล้ว +1

    great video on this topic

  • @zeitreisender2023
    @zeitreisender2023 ปีที่แล้ว

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

  • @fransaucisse9816
    @fransaucisse9816 3 ปีที่แล้ว

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

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

  • @Dablid77
    @Dablid77 3 ปีที่แล้ว +1

    You're an Angel, thank you so much!

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

  • @lkatt7
    @lkatt7 8 หลายเดือนก่อน

    Thank you so much!! Very clearly explained!

  • @XM7D_Abasset
    @XM7D_Abasset 2 ปีที่แล้ว

    Love your channel

  • @ДанилаФедоренко-ч6р
    @ДанилаФедоренко-ч6р ปีที่แล้ว

    THANK YOU MY MAN YOU ARE THE BEST !

  • @ogek7417
    @ogek7417 4 ปีที่แล้ว

    step by step explanation, thank you!

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

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

  • @otnielewu7777
    @otnielewu7777 2 ปีที่แล้ว

    Thank you for this nice tutorial

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

  • @morty_dk
    @morty_dk 3 ปีที่แล้ว

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

  • @ceo-s
    @ceo-s 10 หลายเดือนก่อน

    Very helpful. Thanks

  • @Marki02
    @Marki02 2 ปีที่แล้ว

    good explanation, thank you very much!

  • @batuhanlel9
    @batuhanlel9 3 ปีที่แล้ว

    Thank you. It was really helpful

  • @bushraw66
    @bushraw66 2 ปีที่แล้ว

    thank you very much you are a life saver dude

  • @peterhans8788
    @peterhans8788 2 ปีที่แล้ว

    Good explanation, thank you :)

  • @johanliebert8637
    @johanliebert8637 2 ปีที่แล้ว

    So helpful mate

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

  • @yelimsnusm7551
    @yelimsnusm7551 2 ปีที่แล้ว

    Thanks!! 🤗

  • @zanden69
    @zanden69 2 ปีที่แล้ว

    Thank u so much , now i understand :)

  • @indumathi9523
    @indumathi9523 3 ปีที่แล้ว

    Thanks,u helped me a lot❤️❤️

  • @jacoblamberson3751
    @jacoblamberson3751 4 ปีที่แล้ว

    Thank you my man

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

  • @viettrinh8429
    @viettrinh8429 2 ปีที่แล้ว

    wow, thank you!

  • @mohammadhosseinzolfagharna8106
    @mohammadhosseinzolfagharna8106 2 ปีที่แล้ว

    Thanks dude

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

  • @mykolazhabko3228
    @mykolazhabko3228 3 ปีที่แล้ว

    Thank! It was useful!

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

  • @adriaestevambeltran3395
    @adriaestevambeltran3395 3 ปีที่แล้ว

    Thanks!!!

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

  • @alexbravo7467
    @alexbravo7467 3 ปีที่แล้ว

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

  • @louaykhammar7268
    @louaykhammar7268 3 ปีที่แล้ว

    thanks

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

  • @Jose_T131
    @Jose_T131 ปีที่แล้ว

    Great

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

  • @ronjeremy1232
    @ronjeremy1232 4 ปีที่แล้ว

    tremendous

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

  • @erilshackle
    @erilshackle 3 ปีที่แล้ว

    Woow!

  • @EchoENKO
    @EchoENKO ปีที่แล้ว

    so smart

  • @lilcameauxx
    @lilcameauxx 2 ปีที่แล้ว

    What about parsing through multiple lines?

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว

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

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

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

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

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

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

  • @michaelpatterson1096
    @michaelpatterson1096 2 ปีที่แล้ว

    %[^;] awesome. Great tip!

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

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