简体   繁体   中英

C++ String Length problems

so im practicing the STL string class, but i can not figure out why the string->length function won't come up with the correct answer of 5, and only 2 (no matter the actual length). Here's the program i'm trying to run but it thinks that there are only 2 items between ->begin and ->end:

void testFunc(string _string[])
{
      int _offset = 0;
      string::const_iterator i;
      for (i = _string->begin(); i != _string->end(); i++)
      {
           cout << _offset << "\t";
           cout << _string[_offset] << endl;
           _offset ++;
      }
};

int main()
{
     string Hello[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};

     testFunc(Hello);

     char response;
     cin >> response;
     return 0;
}

The output is:

0     Hi
1     Holla  

Thanks! =)

You're iterating through the first string, which is "Hi" - it has two characters, so you see two entries.

If you want to go all STL, you'd need a vector instead of a C-style array (ie vector<string> , and use an iterator on that.

If you don't want STL:

    void testFunc(string *strings, int stringCount)
    {
        int _offset = 0;

        while (stringCount--)
        {
            cout << _offset << "\t";
            cout << _strings[_offset] << endl;
            _offset ++;
        }
    };

int main()
{
    string Hello[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};

    testFunc(Hello, sizeof(Hello) / sizeof(Hello[0]));

    char response;
    cin >> response;
    return 0;
}

The issue is with the expressions:

_string->begin()
_string->end()

Thinking of a->b as the same as (*a).b , we can see that they are:

(*_string).begin()
(*_string).end()

*x is the same as x[0] , so we have:

_string[0].begin()
_string[0].end()

As _string[0] contains "Hi" , you can see why the iteration is only two steps.

The problem is that you are trying to is iterate a c array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM