user2809184
user2809184

Reputation:

Storing a string by obtaining chars

I'm developing an application in C which requires me to take in a string by building it with a series of chars. The chars are taken in via:ch = fgetc(in_file); and are either a uppercase or lowercase letter. I want to be able to take a series of chars (such as "b u N n y") and assemble them into a string that I can print, store into another file or compare to another string (such as "buNny"). How can I do this in C?

Upvotes: 0

Views: 43

Answers (1)

Dave Lillethun
Dave Lillethun

Reputation: 3108

Seems like what you could do is allocate a char array and put the chars in it, keeping track of where you're at in the buffer so you know where to put the next one. (Don't forget to maintain the \0 at the end, if your string needs to be a valid string after each character is added and not just when everything is done.) You need to keep track of your char array's size so you can tell when it's full by comparing where you're at to the size. When it gets too full, realloc it to a larger size and carry on.

A common thing to do is to double the size of your buffer every time - that keeps the number of times you need to realloc relatively small (compared to the total length of the string). Of course, choosing a good initial value for the size of your buffer can help a lot.

Upvotes: 2

Related Questions