Divide string into chars

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();
}
input[i]

Oh, and your pointer arithmetic works only as long as sizeof(char)==1.
Last edited on
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.



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...
Oke, thank you. The operator [] seems a lot easier to use ;)
Topic archived. No new replies allowed.