Divide string into chars
Sep 18, 2009 at 3:58pm UTC
Hello,
The following programs should divide a string into seperated characters. It works, but is it valid? Is there a better/more standard way to do this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
using namespace std;
int main()
{
string input;
getline(cin,input);
for (int i=0; i<input.length(); i++)
{
const char * ch = input.c_str();
ch += sizeof (char )*i;
cout<<*ch<<" " ;
}
cin.ignore();
}
Sep 18, 2009 at 4:06pm UTC
input[i]
Oh, and your pointer arithmetic works only as long as sizeof(char)==1.
Last edited on Sep 18, 2009 at 4:07pm UTC
Sep 18, 2009 at 4:35pm UTC
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
int main() {
std::string foo = "Hello world" ;
std::copy( foo.begin(), foo.end(),
std::ostream_iterator<char >( std::cout, " " ) );
}
is a better/more standard way.
also:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <string>
int main() {
std::string foo = "Hello world" ;
std::for_each( foo.begin(), foo.end(),
std::cout << boost::lambda::_1 << ' ' );
}
is a better way.
Sep 18, 2009 at 4:35pm UTC
sizeof(char) is guaranteed to equal one.
However, helios 's assessment is correct -- you are assuming something about the size of the elements in your array. And using the operator [] is better anyway...
Sep 18, 2009 at 5:44pm UTC
Oke, thank you. The operator [] seems a lot easier to use ;)
Topic archived. No new replies allowed.