可以用C++写一个例子吗
时间: 2023-03-14 14:44:35 浏览: 62
当然可以!下面是一个使用C语言编写的简单示例:#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
相关问题
用c++写一个strcpy的例子
好的,这是一个使用 C++ 编写的 `strcpy` 函数的例子:
```cpp
#include <iostream>
// 自定义 strcpy 函数
char* strcpy(char* destination, const char* source) {
char* temp = destination;
while (*source) {
*destination++ = *source++;
}
*destination = '\0'; // 添加字符串结束符
return temp;
}
int main() {
const char* source = "Hello, world!";
char destination[20];
// 调用自定义的 strcpy 函数将 source 复制到 destination
strcpy(destination, source);
// 打印复制后的字符串
std::cout << "复制后的字符串: " << destination << std::endl;
return 0;
}
```
在这个例子中,我们定义了一个自定义的 `strcpy` 函数来复制字符串。该函数接受两个参数:目标字符串 `destination` 和源字符串 `source`。通过遍历源字符串中的每个字符,并将其逐个复制到目标字符串中,直到遇到字符串结束符 `\0`。最后,我们在 `main` 函数中调用自定义的 `strcpy` 函数,并打印复制后的字符串。
希望这个例子对你有帮助。如果你有任何问题,请随时提问。
用c++写一个多线程例子
以下是一个使用 C++ 多线程的简单示例,它创建了两个线程并让它们执行不同的任务:
```c++
#include <iostream>
#include <thread>
// 线程函数1
void func1() {
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 1 executing\n";
}
}
// 线程函数2
void func2() {
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
}
}
int main() {
// 创建线程1
std::thread t1(func1);
// 创建线程2
std::thread t2(func2);
// 等待线程1和线程2执行结束
t1.join();
t2.join();
return 0;
}
```
在上面的示例中,我们首先定义了两个线程函数 `func1` 和 `func2`,每个函数都打印一些信息。然后在 `main` 函数中,我们创建了两个线程 `t1` 和 `t2`,它们分别执行 `func1` 和 `func2` 函数。最后,我们使用 `join` 函数等待这两个线程执行结束,然后结束程序。