Question:
C programming question regarding strings?
1970-01-01 00:00:00 UTC
C programming question regarding strings?
Four answers:
Ratchetr
2011-06-01 18:25:27 UTC
There is no function in C that lets you read an arbitrary amount of input from a stream.



Functions like fscanf require an input buffer. That buffer needs to be memory you allocate, either with malloc or on the stack. And if the input is bigger than the buffer...well...bad things can happen.



You can limit how many characters fscanf reads by tweaking the format specifier. That will prevent buffer overflow errors, but it creates a problem: if the format specifier says to read no more than 100 characters, but there are 200 characters to read, then you need to detect that, increase the size of your buffer, and read the rest of the characters...up to your new buffer limit.



You could also just read 1 char at a time, and put it in your buffer (until you hit the end of whatever character). Again, if you fill the buffer, you need to allocate a bigger one (realloc works well for this), and continue the process.



Yes, it's harder than it needs to be. One of many, many reasons why C sucks. (or, at least...why C isn't a 'modern' programming language. Every modern programming language provides a simple [it's a 1 liner] solution to this problem).



Your variable named string MUST point to a buffer that is big enough to hold everything you ask for, or you will crash. It's that simple.
?
2016-11-19 06:59:50 UTC
you're particularly misusing this website. somebody basically replied this question approximately 10 minutes in the past. I study the respond and gave them a thumbs up. Now you have deleted the question & answer and reposted a similar question! what's the clarification for that? you're able to no longer delete your questions when you have gotten solutions.
cld
2011-06-01 18:07:37 UTC
When you mentioned char *string, that reminds me of a header file called string.h(cstring in C++). Maybe that might point to something.
?
2011-06-01 18:31:03 UTC
string is just a pointer -- it does point anywhere yet.

You have to allocate some where h=for it to point.



char * string;

....

string=malloc(512);



then use fgets() to read the string



http://en.wikipedia.org/wiki/Fgets



if your input string exceeds 512 bytes then use realloc to increase you buffer size

read the next buffer of the string and strcat to the original string.

If you still have not got all the string the repeat the above till you have it all,







http://www.java-samples.com/showtutorial.php?tutorialid=589


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...