Hi,
I am having trouble translating the following lines of Visual Basic
code to C.
For iCounter = Len(sReference) To 1 Step -1
iSum = iSum + Val(Mid(sReference, iCounter, 1)) * iMultiplier
Next
fReferenceCheckSum = Right(Str(10 - (iSum Mod 10)), 1)
Any ideas anyone? I have had some help, but I need to know how C's FOR
loops looks like, and how "Val(Mid.." and "Right(Str..." are
translated into C. Any further help would be greatly appreciated.
Kenneth, i didn't know that you didn't know about C. I thought you
didn't know about VB, but now i just don't know which one you don't
know about ? ;-p
Perhaps my using a pointer to iterate through the string, threw you ?
Although, on reread, i was going through the string forward, not
backwards, so that may have played some part if it didn't work, or
maybe i was just plain cold sober.. but TBH, i did expect that you can
adjust that code as needed.
What exactly is this for ? Is this a school project, or do you want it
to just get the VB code to work in C ?
If it's just a conversion, then lose the iterator and the for-next and
use a pointer to go through the string. It's much cleaner.
Anyway, the "for-next" in C is :
for( counter = start; counter > 1; counter--)
where 'start' in your case would be strlen(sReference) or in VB
Len(sReference).
Val(string) in VB returns the numeric value of a String. ie: "48"
yields 48 as a value, not to be confused with Ascii 48 which is 0.
In C, you can do that with atoi(buffer).
value = atoi(buffer);
Mid(buffer, start, length) picks out 'length' number of characters
from 'buffer', starting at 'start'
In C, that can be done with strncpy(), sprintf() etc...
It could be made up like this :
char* mid(buffer, start, len)
{
char *p, *ret;
if (NULL != buffer)
{
/* should check for len and start being ok..but bugger it */
p = &buffer[start];
ret = malloc(sizeof(char) * len + 1);
if (NULL != ret)
{
strcnpy(ret,p,len);
ret[len] = '\0' /* don't remember if it terms or not */
}
}
return ret;
}
Right$(buffer, length) returns the rightmost 'length' characters from
'buffer'.
A C version may be :
char* Right(char* buffer,long len)
{
char* p = buffer, long blen;
if(NULL != p)
{
blen = strlen(p);
if (len < strlen(p))
p = &buffer[blen - len];
}
return p;
}