Adding up a text string!

Discussion in 'C++' started by Miranda Comerasamy, Oct 8, 2012.

  1. Miranda Comerasamy

    Miranda Comerasamy New Member

    Joined:
    Oct 8, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    I am new to C++ programming and I have come across my first dilemma. I am doing a project and I need to add up the letters of a word i.e text string so that it gives me a mathematical answer. For example the word cake will give me four letters so I need to return an answer of four.
    Can you help me, please.

    Thank you.
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    if you're using a char array, you can use strlen to find the number of chars; if you're using the string class, you can use the member function length to find the number of chars.

    Code:
    ... // bits of code
    
    #include <string>   // string class
    #include <cstring>  // c string functions
    
    ... // bits of code
    
    char c_word[] = "test";
    std::string s_word = "test";
    
    strlen(c_word); // used on terminated char arrays
    or
    strlen(s_word.c_str()); // can be used on string class objects
    or
    s_word.length();         // applies to string class objects only
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice