如何解决如何使用write显示字符串?
对于练习,我必须使用此原型显示一个字符串/字符链:
void display(char *str);
我没有使用'printf'的权利,但是我不得不使用'write'。
有人可以解释我的工作原理吗?
除写!!!!我无权使用任何功能!
解决方法
像这样(我假设您是指* nix write
函数):
#include <unistd.h>
// EDIT: now without using string.h
size_t my_strlen(char const *str)
{
size_t ret = 0u;
while (str[ret++] != '\0')
;
return ret;
}
void display(char const *str)
{
write(STDOUT_FILENO,str,my_strlen(str));
}
,
一个自包含且高效的display
函数:
void display(char const *str) {
int length = 0; // string length
const char *pch = str; // pch points to start of string
while (*pch++) // loop thtough string until the end of string
length++;
write(STDOUT_FILENO,length); // write the string in one go
}
,
由于您无法使用任何其他功能,因此我将使用此功能:
#define MAX_LENGTH 256
void display(char const *str) {
int lastIndex;
for(lastIndex=0; str[lastIndex]!='\0' && lastIndex<MAX_LENGTH; lastIndex++) {}
write(STDOUT_FILENO,lastIndex);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。