当前位置: 动力学知识库 > 问答 > 编程问答 >

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 (i.e. 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: