-
chars and pointers
My code is generaing a compile error on the append line. it doesn't like ch[1]. i tried "ch" which compiled fine but gives the pointer or something else very very odd.
The function sends in a line of numbers and characters and returns just the numbers. Useful for stripping numeric fields of common delimiters (-,.#)
Code:
void ReduceVal(std::string& strval)
{
char ch[1];
std::string::iterator p = strval.begin();
std::string newval = "";
while(p != strval.end())
{
ch[1] = (char) (*p);
if (isdigit(ch[1]))
{
newval.append(ch[1]);
}
p++;
}
strval = newval;
}
-
Well ch[1] is only one char, and it's subscript is therefore ch[0]
-
SO I defint it as char ch[1] but I reference it as ch[0]?
-
-
quick fix'd
Code:
if (isdigit(ch[1]))
{
tempval = ch[1];
newval.append(tempval);
}
-
Why are you even using an array of 1 characters when a simple ch will suffice?
I doubt your fix, given your prior declarations - it's still an out of bound access even if it seems to be working.
-
>> SO I defint it as char ch[1] but I reference it as ch[0]?
Arrays use zero-based indexes in C++. When you define the array, the number in the brackets is the size. If you put 10, then your array will have room for ten characters. If you put 1, your array will have room for 1 character. When you use the array, the number in the brackets is the index. Since indexes start at zero, the valid indexes are 0 through (size-1). So for an array of size 10, indexes 0-9 are valid. For an array of size 1, only index 0 is valid.
As for your code, if (isdigit(*p)) should work fine.
-
THanks for the help. I've reviewed it and was able to shorten it.
Code:
void ReduceVal(std::string& strval)
{
std::string::iterator p = strval.begin();
std::string newval = "";
std::string tempval = "";
while(p != strval.end())
{
if (isdigit(*p) )
{
tempval = *p;
newval.append(tempval);
}
p++;
}
strval = newval;
}
-
You don't need to set new string values to "", the default constructor will automatically make them empty:
Code:
std::string newval;
Also, tempval is unnecessary. To append a single character to a string you can use any of the following:
Code:
newval += *p;
newval.push_back(*p);
newval.append(1, *p);
-