+ 2

[Solved] Other ways to take sentences one word at a time?

G'day, I've used do{ *temp=0; scanf("%s ",temp); // ....the rest of my code within the loop }while(*temp!=0); This seems to work, but I remember that I shouldn't be using scanf in the real world (outside of SoloLearn). What are the other methods that I should be trying to use? https://code.sololearn.com/cBd8Wzeidx4u/?ref=app

13th Feb 2022, 5:57 AM
HungryTradie
HungryTradie - avatar
1 Answer
+ 9
There is no danger in using scanf if you limit the buffer size. Without limit, scanf is like gets and susceptible to buffer overflow. With limit, it acts more like fgets. The other issue with scanf is expectation. If you scanf text you expect it to be formatted a specific way. With user input, this will likely not always be the case. But I don't think that scanf itself will cause problems, rather it breaks the logic of your application if tainted input is used without any validation. I personally prefer to read input as a line (fgets). You have later functions like sscanf at you disposal. What you want to do, splitting text into tokens, can easily be done using strtok on the string in memory. Remember, strtok is destructive. If you need the origjnal string then you need to work with a copy.
13th Feb 2022, 6:19 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar