C is not a managed language, and it's been a while since I have used an unmanaged language. I need to create a block of code which searches through a character array, and replaces all instances of '2' with 'Ba'. This is quite simple, except for the fact that now the resulting string will be larger than the original, so I need to account for this somehow, and I don't remember how to do this.
Here is try number 4, using pointers:
//Move next 150 characters after replacing all 2 with Ba:
numberread = read(XYZFile, datatoreadWWW, sizeof(datatoreadWWW));
int y = strlen(datatoreadWWW); //should be 150.
int additionallength = y;
i = 0;
while(i < y) {
if(datatoreadWWW[i] == '2') {
additionallength++; //Since we need to replace any '2' with 'Ba', we should add one character for the a.
}
i++;
}
//And now use additionallength to create the new char array to be placed in WWW, called newstring:
char newstring[additionallength];
int j = 0;
const char *in = datatoreadWWW;
char *out = newstring;
while(*in) {
if (*in == '2') {
*out++ = 'B';
*out++ = 'a';
}
else {
*out++ = *in;
}
in++;
}
*out++ = '\0';
And I'm still confused/stuck on this, I'm getting garbage values written into the WWW file such as "^Q" and such. Not sure what that means, but it doesn't seem correct.
Edit: The program above seems to be working now. The problem was, if anyone ever reads this post as a resource, that I was adding +1 to additionallength, but this was happening in every iteration, so every so many characters there was an extra empty, null space being put in to the file, which was incorrect. Regardless, I think we've learned that is important to review pointers whenever working in C, as this is the easiest way to accomplish this.
'Ba'is a multi-byte character constant , it is still a single character after all that. What you actually want is two characters,'B'and'a'. As you say, you need to have enough space because the result will be larger than the original. Try writing some code and then posting it.