Monday, May 24, 2010

C programming language?

How do you allow spaces when using the scanf() function??





I'm just learning C, and the part of the book I'm in is teaching about scanf(), but when running the program, unless I only use one word it uses the second word for the next scanf()!!!!!





Here is what happens.





What is supposed to happen is.....





Enter an adjective:Fufy


Enter a food:Marshellow


Enter a household chore (Past tence):Cleaned


Enter an item of furniture:Cair








Don't touch that Fufy Marshellow!!


I just Cleaned the Cair!!





Now what it does if two or ree ors are used....





Enter an adjective:Fluffy Marshmellow


Enter a food:Enter a household chore (Past tence):Taking out the trash


Enter an item of furniture:





Don't touch that Fluffy Marshmellow!!


I just Taking the out!!





So how do I allow spaces??

C programming language?
You haven't showed us the actual code that does the reading of the text...





scanf can do lots of things, it depends on how you use it and what you pass to it that controls what it does.





scanf("%s", ...) will I believe read the next white-space delimited string. However, you should never ever use scanf("%s", ...) because you cannot predict how many bytes it will read so you do not know what size buffer to supply.





The problem you have is that your input is terminated by the end of the line, but you have written code that terminates the input on any white space.





To do it correctly, you need to write low level code in a loop that reads input character by character and puts it into a buffer. It should loop until you get a "new line" character, '\n'. You should make sure you don't get buffer overrun, either by reallocating to a bigger buffer or truncating the input when you reach the limit. You will need to nul-terminate your input string so that you can print it out correctly.
Reply:fstream treats spaces as a new word .......... so to allow spaces you need to replace fstream with other statement like getline


No comments:

Post a Comment