Question:

How can I read char by char from a string in C++?

by  |  earlier

0 LIKES UnLike

I've been meaning to read char by char from a string.

For example if I have a string= "Hello";

That I should get 5 chars:

'H'

'e'

'l'

'l'

'o'

any help on what do to?

Thanks!!!

 Tags:

   Report

4 ANSWERS


  1. You can do like this:

    #include <string>

    using namespace std;

    int main()

    {

    char list[5];

    string h = "hello";

    for(int i=0; i<h.length(); i++)

    {

    list[i] = h.at(i);

    //what do I have to do to read each character

    //on that string? :( not read from a char array...

    }

    return 0;

    }

    Good luck,

    peng

    http://www.eptop.com


  2. If you need help check out http://www.pchelpdoc.com

    There is tons of help on there for free.

    Good Luck.  

  3. I would declare the string as a pointer to char like this:

    const char *string = "Hello";

    Then read it like an array (which it basically is) :

    int i;

    for (i = 0; i < strlen(string); i++) cout << string << endl;

    You would get:

    H

    e

    l

    l

    o

    \n


  4. You can create a null-terminated character array from a string, and use the character array as you would a C-style char array. Like this:

    #include <iostream>

    #include <string>

    using namespace std;

    int main(int argc, char *argv[]) {

      string s("hello");

      const char *p = s.c_str();

      while (*p != '\0') cout << *p++ << endl;

      return 0;

    }

    You should not change the value of any character in the array you get from c_str().

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.