puts() 与 printf() 的对比

    在C中,给定一个字符串变量str,应该首选下面哪一个用于将str打印到标准输出?

1) puts(str);
2) printf(str);

    puts() 可以优先用于打印字符串,因为它通常成本较低(puts() 的实现通常比printf() 简单),并且如果字符串具有格式化字符(如“%s”),则 printf() 将给出意外的结果。另外,如果str是用户输入字符串,那么使用 printf() 可能会导致安全问题。
    还要注意 puts() 将光标移动到下一行。如果不希望光标移到下一行,则可以使用 puts() 的以下变体:

fputs(str, stdout)

    您可以尝试以下程序来测试上面讨论的 puts() 和 printf() 之间的差异。
    程序1:

// C program to show the use of puts
#include <stdio.h>
int main()
{
	puts("Geeksfor");
	puts("Geeks");

	getchar();
	return 0;
}

    程序2:

// C program to show the use of fputs and getchar
#include <stdio.h>
int main()
{
	fputs("Geeksfor", stdout);
	fputs("Geeks", stdout);

	getchar();
	return 0;
}

    程序3:

// C program to show the side effect of using
// %s in printf
#include <stdio.h>
int main()
{
	// % is intentionally put here to show side effects of
	// using printf(str)
	printf("Geek%sforGeek%s");
	getchar();
	return 0;
}

    程序4:

// C program to show the use of puts
#include <stdio.h>
int main()
{
	puts("Geek%sforGeek%s");
	getchar();
	return 0;
}
参考文档

[1]GeeksforGeeks.puts() vs printf() for printing a string[EB/OL].https://www.geeksforgeeks.org/puts-vs-printf-for-printing-a-string/,2021-05-27.

好的!接下来我们继续扩展之前的对比,加入 **Java** 和 **C语言** 来比较四门语言(Python、Go、Java 和 C)的特点及其实现类似功能的方式。 --- ### 功能回顾: 仍然以前面提到的“从网络并行下载多个文件”作为核心功能来进行代码对比。 --- ## Java 实现: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileDownloader { public static void main(String[] args) throws Exception { String[] urls = { "https://example.com/file1.txt", "https://example.com/file2.txt", "https://example.com/file3.txt" }; ExecutorService executor = Executors.newFixedThreadPool(3); for (String url : urls) { Runnable worker = new DownloadTask(url); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) {} System.out.println("All downloads completed."); } } class DownloadTask implements Runnable { private final String fileUrl; public DownloadTask(String fileUrl) { this.fileUrl = fileUrl; } @Override public void run() { try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream inputStream = connection.getInputStream(); String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); FileOutputStream outputStream = new FileOutputStream(fileName); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("Downloaded: " + fileName); } catch (Exception e) { System.err.println(e.getMessage()); } } } ``` #### 特点: - Java 提供强大的并发工具包 `java.util.concurrent`,支持多种线程池配置。 - 面向对象的设计使得程序结构清晰且易于复用。 - 性能介于动态解释型语言(如 Python)和底层系统级语言之间。 --- ## C语言实现: 由于 C 没有直接内建对 HTTP 协议的支持以及高级别的多线程 API,这里仅提供基本框架用于参考: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define MAX_URLS 3 void *download(void *arg) { char *url = (char *) arg; // 这里省略了实际的HTTP请求逻辑 printf("Download complete: %s\n", url); free(arg); // Free allocated memory after use. pthread_exit(NULL); } int main(int argc, char const *argv[]) { pthread_t threads[MAX_URLS]; char *urls[MAX_URLS] = {"http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt"}; for (size_t i = 0; i < MAX_URLS; ++i){ char *str = strdup(urls[i]); // Duplicate strings since arguments are passed to thread by value. if(pthread_create(&threads[i], NULL, download, str)){ fprintf(stderr,"Error creating thread.\n"); return EXIT_FAILURE; } } for(size_t j=0;j<MAX_URLS;++j){ if(pthread_join(threads[j],NULL)){ fprintf(stderr,"Error joining thread.\n"); return EXIT_FAILURE; } } puts("All downloads finished."); return EXIT_SUCCESS; } ``` 注意:完整版还需要引入第三方库例如 libcurl 完成真实的网络请求部分. #### 特点: - 极低级别控制硬件资源的能力使其成为嵌入式设备等领域的重要选择。 - 缺乏高层次的数据抽象能力意味着开发者往往需要手动管理更多细节,比如内存分配等。 --- ### 综合分析表 | 四种语言特性对比 | 方面 | Python | Go | Java | C | |--------------------|------------------------|-------------------------|--------------------------|-----------------------| | 开发效率 | ★★★★☆ | ★★★☆☆ | ★★★★☆ | ★★☆☆☆ | | 并发性能 | ★☆☆☆☆ | ★★★★☆ | ★★★☆☆ | ★★★★☆ | | 易读性 | ★★★★☆ | ★★★☆☆ | ★★★★☆ | ★☆☆☆☆ | | 系统交互能力 | ☆☆☆☆☆ | ★★☆☆☆ | ★★★☆☆ | ★★★★★ | 注释:“星数越多表示该维度越强”。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值