我是一名新計算機科學專業的學生,??我有一個家庭作業問題如下:
撰寫一個傳入 C 字串的函式,并使用指標確定字串中的字符數。
這是我的代碼:
#include <iostream>
#include <string.h>
using namespace std;
const int SIZE = 40;
int function(const char* , int, int);
int main()
{
char thing[SIZE];
int chars = 0;
cout << "enter string. max " << SIZE - 1 << " characters" << endl;
cin.getline(thing, SIZE);
int y = function(thing, chars, SIZE);
cout << y;
}
int function(const char *ptr, int a, int b){
a = 0;
for (int i = 0; i < b; i ){
while (*ptr != '\0'){
a ;
}
}
return a;
}
uj5u.com熱心網友回復:
首先歡迎來到stackoverflow ye0123!我認為您正在嘗試在strlen()這里重寫該功能。嘗試查看以下鏈接查找指標指向的字串的大小。簡短的回答是您可以使用該strlen()函式來查找字串的長度。您的函式的代碼將如下所示:
int function(const char *ptr)
{
size_t length = strlen(ptr);
return length;
}
你也應該只需要這個函式和 main。
strlen()編輯:也許我誤解了你的問題,畢竟你應該重新發明。在這種情況下,您可以這樣做:
unsigned int my_strlen(const char *p)
{
unsigned int count = 0;
while(*p != '\0')
{
count ;
p ;
}
return count;
}
這里我比較*p的'\0'是'\0'空終止字符。
這取自https://overiq.com/c-programming-101/the-strlen-function-in-c/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433863.html
上一篇:簡化代碼片段-圓圈中的矢量旋轉
