c++ puts和printf有什么区别
时间: 2023-10-18 09:04:13 浏览: 47
puts和printf都可以用来输出字符串,但它们有一些区别:
1. puts会自动在输出的字符串后面加上一个换行符,而printf不会。所以,如果你想在使用printf输出字符串时也加上换行符,需要在格式化字符串中加上\n。
2. puts只能输出字符串,而printf可以输出多种类型的数据,比如整数、浮点数等。
3. puts没有返回值,而printf返回输出的字符数。
举个例子:
```c++
char str[] = "Hello World!";
// 使用puts输出字符串
puts(str);
// 使用printf输出字符串,并加上换行符
printf("%s\n", str);
// 使用printf输出整数
int num = 10;
printf("The number is %d\n", num);
```
输出结果:
```
Hello World!
Hello World!
The number is 10
```
相关问题
puts(strings);在c++中是什么意思
`puts(strings)` 是一个 C/C++ 标准库中的函数,用于输出一个字符串。
具体来说,它会将一个以 null 结尾的字符串 `strings` 输出到标准输出流(通常是屏幕),并自动在字符串末尾添加一个换行符。例如:
```c++
char str[] = "Hello, world!";
puts(str); // 输出 "Hello, world!\n"
```
需要注意的是,`puts` 函数有以下特点:
1. 它不需要指定字符串的长度,因为它会自动寻找字符串的结尾;
2. 与 `printf` 函数不同,它不能输出格式化字符串;
3. 它会自动在字符串末尾添加一个换行符,因此可以直接输出一整行字符串。
在 C++ 中,还有一种更为常用的输出字符串的方法是使用 `std::cout` 对象,例如:
```c++
#include <iostream>
int main() {
char str[] = "Hello, world!";
std::cout << str << std::endl; // 输出 "Hello, world!" 并换行
return 0;
}
```
这种方法也不需要指定字符串长度,并且可以通过使用流操作符 `<<` 输出各种类型的数据。
C++实现有向图最长路径
以下是C++实现有向图最长路径的示例代码,假设有n个结点和m条有向边:
```c++
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
const int M = 200010;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int dist[N], cnt[N];
bool st[N];
int q[N];
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
bool spfa() {
int hh = 0, tt = 0;
memset(dist, -0x3f, sizeof dist);
dist[1] = 0;
q[tt++] = 1;
st[1] = true;
while (hh != tt) {
int t = q[hh++];
if (hh == N) hh = 0;
st[t] = false;
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] < dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true; // 存在正环
if (!st[j]) {
q[tt++] = j;
if (tt == N) tt = 0;
st[j] = true;
}
}
}
}
return false;
}
int main() {
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
while (m--) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
if (spfa()) puts("-1");
else printf("%d\n", dist[n]);
return 0;
}
```
其中,add函数用于添加一条有向边,spfa函数用于求解最长路径,即使用SPFA算法判断是否存在正环,如果存在则返回-1,否则返回n号结点的最长路径。