如何在不使用C语言的标准库的情况下显示字符串值?请参阅以下代码:
//without using the standard libraries that other created it
int main() {
string str = "Hello";
//How do I can display str value without using the standard libraries that other created it?
}
答案 0 :(得分:3)
以下是如何做到的:
// Declare the prototype for the write() function,
// with unspecified parameters because why not.
extern long write();
int main(void) {
char const *str = "Hello";
// Retrieve the length
unsigned long size = 0;
while(str[size])
++size;
// Write to stdout (fd 1)
write(1, str, size);
return 0;
}
当然,它是不可移植的,并且可能无法在大多数系统上链接或触发UB,而不是我从其中提取声明的系统(它是Linux系统)调用,在我从Coliru检索的unistd.h
中声明的。但那么,这就是为什么我们首先拥有标准库的原因。
答案 1 :(得分:1)
很简单,你不能,至少不能,如果你想让你的代码完全可移植。
几乎可以肯定,某种方式可以在不使用标准库的情况下在C代码中执行输出。但是,从一个系统到另一个系统,这样做的方式会有很大差异。例如,在UNIX系统上运行的解决方案几乎肯定无法在Windows上运行,反之亦然 - 除非该解决方案使用为每个系统定制的C标准库。
这就是标准库存在的原因。对于不支持标准库的独立(嵌入式)实现,您必须编写特定于系统的代码来执行任何I / O.
如果您想知道如何在不使用标准库的情况下在特定系统上执行I / O ,我建议发布一个新问题。
int main() {
string str = "Hello";
}
int main()
最好写成int main(void)
。
C中没有类型string
。您可能想要的是
const char *str = "Hello";
或
char str[] = "Hello";
C中的“字符串”根据定义是“由第一个空字符终止并包括第一个空字符的连续字符序列”。它是一种数据格式,而不是数据类型。 (C ++有一个类型std::string
,但你问的是C,而不是C ++ - 而在C ++ std::string
本身是由C ++标准库定义的。)
comp.lang.c FAQ是一个很好的资源。