Check if something wrote into char array?

Feb 14, 2012 at 1:45pm
Hi I am currently trying to figure out how to check if something wrote into a char array after it got initialized.

Here's a more detailed description of my problem with some code:
1
2
3
4
5
6
7
8
9
10
11
12
formatString(char* data){
	char name[64];
	char value[128];
	char* line = strtok( data, "\n" );

	while( line != NULL )
	{
		sscanf(line, "%[^=]=%s", name, value);
		//both arrays get stored in a list here
		line = strtok( NULL, "\n" );
	}
}

Now if data would theoratically be "key1=value1key2=value2key3=value3key4=value4" then this would be stored in my list like this (there are newlines formatted within the string):
[1]name="key1", value="value1"
[2]name="key2", value="value2"
[3]name="key3", value="value3"
[4]name="key4", value="value4"

This works good as long as the incoming string is formated like this but if for example a value contains nothing (like this: "key1=key2=value2key3=value3") then sscanf returns 1 instead of 2 (because only one array could be written into) and the array still has the unwritten values stored (which I am trying to avoid)

I could solve this easily by checking the return of sscanf and writing "" into the value array but this would only be a solution for this special case.

So now back to my question, how can I check if the array contains after its initialization?
Or a different question for this specific code would be, is there a way to find out which string sscanf didnt write into?
Last edited on Feb 14, 2012 at 1:47pm
Feb 14, 2012 at 3:37pm
closed account (DSLq5Di1)
The character arrays haven't been initialized, they'll contain whatever junk is in memory if sscanf has not written to them. Initialize them as empty strings and you simply need to check if the first character is null,

1
2
3
4
char name[64] = "";
...

if (name[0] == '\0') // empty string 
Feb 14, 2012 at 4:36pm
Of course, I guess I was blind back then :D

Thanks for the help.
Topic archived. No new replies allowed.