James Kanze
10/16/2008 9:08:00 AM
On Oct 16, 1:43 am, Atropo <lxvasq...@gmail.com> wrote:
> Having several strings how do I construct variable to pass to
> system():
> Lets say the date command
> string str = "14/10/08 19:06:09";
> strDD = str.substr(0,2);
> strMM = str.substr(3,2);
> strYY = str.substr(6,2);
> strhh = str.substr(9,2);
> strmm = str.substr(12,2);
> strss = str.substr(15,2);
Hmmm. I'd use boost::regex for this, checking the format at the
same time.
Also, you don't show the definitions; I'm supposing that strDD,
et al. are all std::string.
> // I would like contruct date -u 1014190608.09 2>&1 > /dev/
> null
> strT<<"date -u "<<strMM<<strDD<<strhh<<strmm<<strYY<<"."<<strss<< "
> 2>&1 >/dev/null;"<<endl;
Again, you don't show the definition of strT. Given the use,
I'll suppose it's an std::ostringstream...
> system(strT);
Which isn't an appropriate type for system(). You need a char
const*. If strT is an std::ostringstream, this means:
system( strT.str().c_str() ) ;
> when I compile it throws
> rtchk.cpp: In function `int main (int, char **)':
> rtchk.cpp:59: no match for `string & << const char[9]'
Not having the actual sources, it's very difficult to know
where line 59 is. But since the error message is complaining
about an << operator into string (and not std::string? curious),
I'll guess that you declared strT as a string (whatever that
is), and not as an std::ostringstream.
> so i could be a syntax error, but I'm newbie and don't know.
Not a syntax error, but a type error. You need to learn about
data types.
The classical way of writing this would be something like:
void
setDate( std::string const& userDateString )
{
static boost::regex const
matcher(
"^(\\d\\d)/(\\d\\d)/(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d)
$" ) ;
enum DateFmt { date, day, month, year, hour, minute,
second } ;
boost::match_results< std::string::const_iterator >
fields ;
if ( ! boost::regex_match( userDateString, fields, matcher ) )
{
throw std::runtime_error( "Illegal date" ) ;
}
std::ostringstream builder ;
builder.fill( '0' ) ;
builder << "echo date -u "
<< std::setw( 2 ) << fields[ month ]
<< std::setw( 2 ) << fields[ day ]
<< std::setw( 2 ) << fields[ hour ]
<< std::setw( 2 ) << fields[ minute ]
<< std::setw( 2 ) << fields[ year ]
<< '.' << std::setw( 2 ) << fields[ second ] ;
if ( system( builder.str().c_str() ) != 0 ) {
throw std::runtime_error( "Attempt to set date failed" ) ;
}
}
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34