C++ C++;字符串长度问题
所以我在练习STL字符串类,但我不明白为什么string->length函数不能给出正确答案5,而只有2(不管实际长度)。这是我试图运行的程序,但它认为->开始和->结束之间只有两项:C++ C++;字符串长度问题,c++,string,stl,C++,String,Stl,所以我在练习STL字符串类,但我不明白为什么string->length函数不能给出正确答案5,而只有2(不管实际长度)。这是我试图运行的程序,但它认为->开始和->结束之间只有两项: void testFunc(string _string[]) { int _offset = 0; string::const_iterator i; for (i = _string->begin(); i != _string->end(); i++)
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;
}
谢谢!=)问题是您正在尝试迭代一个c数组。问题是您正在尝试迭代一个c数组。您正在迭代第一个字符串,即“Hi”-它有两个字符,因此您会看到两个条目 如果你想全部使用STL,你需要一个向量而不是一个C风格的数组(即
vector
),并在上面使用迭代器
如果您不想要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;
}
void testFunc(string*strings,int stringCount)
{
int _offset=0;
而(stringCount--)
{
cout您正在遍历第一个字符串,即“Hi”-它有两个字符,因此您会看到两个条目
如果你想全部使用STL,你需要一个向量而不是一个C风格的数组(即vector
),并在上面使用迭代器
如果您不想要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;
}
void testFunc(string*strings,int stringCount)
{
int _offset=0;
而(stringCount--)
{
cout问题在于表达方式:
_string->begin()
_string->end()
考虑到a->b
与(*a).b
相同,我们可以看到它们是:
(*_string).begin()
(*_string).end()
*x
与x[0]
相同,因此我们有:
_string[0].begin()
_string[0].end()
由于\u string[0]
包含“Hi”
,您可以看到为什么迭代只需两个步骤。问题在于表达式:
_string->begin()
_string->end()
考虑到a->b
与(*a).b
相同,我们可以看到它们是:
(*_string).begin()
(*_string).end()
*x
与x[0]
相同,因此我们有:
_string[0].begin()
_string[0].end()
由于\u字符串[0]
包含“Hi”
,你可以看到为什么迭代只需两步。如果我不需要全部使用STL,我该怎么做?谢谢你的回答!C数组没有内置大小,所以你需要将它传递到函数中。让我编辑我的答案。数组总是有一个特定的固定大小。@GMan:我的重点是一个接收数组thr的函数虽然指针无法检索大小。当然,这并不是特别清楚。如果我不需要全部使用STL,我该怎么做?谢谢你的回答!C数组没有内置大小,所以你需要将其传递到函数中。让我编辑我的答案。数组总是有一个特定的固定大小。@GMan:my point是指通过指针接收数组的函数将无法检索大小。诚然,这一点并不是特别清楚。