Re: std::string find_first_of and replace
On Thursday, 10 July 2014 02:50:08 UTC+3, Christopher Pisz wrote:
My code below is not behaving as expected. I want to transform
"11/21/13" into "11-21-13"
My loop never exits and the first time through pos = 1, when I would
think it should be 2. Then after the first replace the debugger says my
string is
""1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\
x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1/22/2001"
and I don't know where the heck 1x is coming from.
Any hints?
Turn on warnings about suspicious implicit conversions if the
compiler that you use emits such warnings. It is nuisance in C++
that conforming implementation is required to convert so lot of
things implicitly.
I am in difficulties to form better hints ... bad imagination.
I just say straight out what I think is wrong in your code, you
judge yourself.
#include <iostream>
#include <string>
//--------------------------------------------------------------------------
------------------------
bool Transform_DatetimeString(const std::string & fromXml, std::string &
toSql)
{
toSql = fromXml;
std::string::size_type pos = std::string::npos;
Here you initialize a variable 'pos' despite its value is
assigned on very next line again. Not an error, just pointless.
while( pos = toSql.find_first_of('/') != std::string::npos )
{
Here you use too complex for you expression as 'while' condition
and/or do not use parentheses where you are unsure about operator
precedence.
The 'operator=' has lower precedence than 'operator!=' so value
of 'pos' won't be a position in string (like you likely expect) but
bool value 'true' converted to int (IOW 1).
toSql = toSql.replace(pos, 1, '-', 1);
Here this replacement does not likely do what you expect
(and likely won't even if you fix previous issue). I think
so because the compiler likely picks
string& string::replace(size_t pos, size_t len, size_t n, char c);
from (overly huge for my taste) set of overloads of 'replace' it has.
}
return true;
}
Rest of your code felt OK to me.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]