-2

I'm trying to get the number of characters in the string without using any library functions.

I'm getting an "array initializer must be an initializer list or literal string" error.

using namespace std;

string stringLength(string myString) {


char string[] = myString.c_str();

while (string[i] != 0) {

//code to calculate length of char string[]

}    

int main() {

string myString = "hello";

cout << stringLength(myString) << endl;

cout << myString << endl;

return 0;
}
  • Cause of error is the way you defined the string. `char string[] = ` demands that the next token be a string literal (`"Hi! I'm a string literal!"`) or a constant character array (`{'H', 'i', '!', ' ', 'I', '\', 'm', ' ', 'a', ' ', 'c', 'h', 'a', 'r', ' ', 'a', 'r', 'r', 'a', 'y', '!'}`) – user4581301 Nov 06 '15 at 02:33

3 Answers3

2

You have not one but two member functions at your disposal for determining the length of a std::string: size() and length(). You can just use them:

int main() {
    string myString = "hello";
    cout << myString.length() << endl;
    cout << myString << endl;
    return 0;
}

If you really, really insist on doing it the old-fashioned C way, don't. But then the right way to pull out the internal character pointer is via either c_str() or data()

Barry
  • 286,269
  • 29
  • 621
  • 977
0

what @Barry do is the correct way
but if this is what you want, check this:

#include <string>
#include <iostream>

using namespace std;

size_t stringLength(string myString) {
    size_t count = 0;
    const char * pstr = myString.c_str();
    while (pstr[count] != 0) {
        //code to calculate length of char string[]
        ++count;
    }
    return count;
}    

int main() {
    string myString = "hello";
    cout << stringLength(myString) << endl;
    cout << myString << endl;
    return 0;
}
user2986683
  • 297
  • 1
  • 4
  • 12
0

myString.c_str() returns pointer to string.

const char* str = myString.c_str();

int length = 0;
while (*str != NULL) {
length++;
str++;
}
Nandu
  • 808
  • 7
  • 10