[英]Char array length function
有誰知道如何編寫一個 function 來計算示例中給出的數組長度?
cout << length(argv[1]) << endl;
我試過這樣的東西,但它說那時不能有 function lentgh。
for(int i = 0; myStrChar[i] != '\0'; i++)
{
count++;
}
EDIT1:這是代碼的 rest:
#include <iostream>
#include<cstring>
using namespace std;
int i;
int length()
{
for(int i = 0; myStrChar[i] != '\0'; i++)
{
count++;
}
}
int main()
{
cout << "Hello world!" << endl;
cout << "length of first text: ";
cout << length(argv[1]) << endl;
char tab[255] = {"Ana has a cat"};
EDIT2:現在我做了這樣的事情,但它輸出 108 作為文本長度
char argv[]="ana has a cat";
int length(char l)
{
int cou= 0;
for(int i = 0; i!=0; i++)
{
cou++;
return cou;
}
}
嗯,怎么了? 這是一個有效的代碼 - 只需將其包裝到 function 中:
size_t length(const char* myStrChar)
{
size_t count = 0;
for(int i = 0; myStrChar[i] != '\0'; i++) {
count++;
}
return count;
}
你可以做的更短一點:
size_t length(const char* myStrChar)
{
size_t count = 0;
for (; myStrChar[count] != 0; count++)
/* Do nothing */;
return count;
}
UPD:這是來自問題的代碼和我對作者的評論:
// You're passing just a single character to this function - not array
// of char's - not a string.
// Pass char* or better const char*.
int length(char l)
{
int cou= 0;
// Ok, this loop does nothing - it's going to stop at the
// first condition check, because you assign 0 to i
// and immediately check if it is not zero - this check will
// return false and the loop will never start.
// Check the current symbol in string if it is not zero
for(int i = 0; i!=0; i++)
{
cou++;
// Even if you'll fix mistakes above, your loop will stop
// at the first iteration, because of this return.
// You must put it right after the loop.
return cou;
}
// Your function actually returns nothing, because no iterations
// of the loop above is performed - so no return statement reached
// at all - it is undefined behaviour :(
// Put return here out of the loop;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.