如何计算 C++ 中 C_String 中的字符数?
我是一名计算机科学专业的新生,我有一个家庭作业问题如下:
编写一个函数,传入 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;
}
I'm a new Computer Science student, and I have a homework question that is as follows:
Write a Function that passes in a C-String and using a pointer determine the number of chars in the string.
Here is my code:
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您正在尝试在这里重写
strlen()
函数。尝试查看以下链接 查找 a 的大小指针指向的字符串。简而言之,您可以使用 strlen() 函数来查找字符串的长度。您的函数的代码将如下所示:
您还应该只需要此函数和 main。
编辑:也许我误解了你的问题,毕竟你应该重新发明
strlen()
。在这种情况下,您可以这样做:这里我将
*p
与'\0'
进行比较,因为'\0'
是空终止符。这是取自 https://overiq.com/c -programming-101/the-strlen-function-in-c/
I think you are trying to rewrite the
strlen()
function here. Try giving the following link a look Find the size of a string pointed by a pointer.The short answer is that you can use the
strlen()
function to find the length of your string. The code for your function will look something like this:You should also only need this function and main.
Edit: Maybe I misunderstood your question and you are supposed to reinvent
strlen()
after all. In that case, you can do it like so:Here I am comparing
*p
from'\0'
as'\0'
is the null termination character.This was taken from https://overiq.com/c-programming-101/the-strlen-function-in-c/