在c++中怎样从string字符串“3.5+3.6+3.7”中的小数输出出来
时间: 2023-06-07 11:08:47 浏览: 54
您可以使用库函数 atof() 将字符串转换为浮点数,然后输出即可。
示例代码如下:
```
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.5 3.6 3.7";
char *ptr = str;
float num;
while (*ptr) {
num = atof(ptr);
printf("%.1f ", num);
while (*ptr && (*ptr != ' ')) ptr++;
while (*ptr && (*ptr == ' ')) ptr++;
}
return 0;
}
```
输出结果为:
```
3.5 3.6 3.7
```
相关问题
C++中字符串可以,"AA"+"BB"这样拼接输出吗
在C++中,字符串是通过`std::string`类来处理的,如果你想像`AA"+"BB`那样直接拼接字符串,会遇到问题。`+`运算符用于连接基本数据类型(如整数、字符)或特定类型的字符串,但不会自动处理`std::string`对象。如果你有两个`std::string`对象`AA`和`BB`,你需要使用`+`操作符的重载版本,即`std::string::append()`方法或者`+=`运算符来实现拼接。
这里是两种常见的拼接方式:
1. 使用`append()`方法:
```cpp
std::string AA = "AA";
std::string BB = "BB";
AA.append(BB);
```
2. 使用`+=`运算符:
```cpp
std::string AA = "AA";
AA += "BB";
```
这两种方式都会将`BB`追加到`AA`的末尾,生成`"AABB"`。
c++ printf输出string类型的中文字符串
在 C++ 中,可以使用 `std::string` 类型来存储字符串。如果要输出一个中文字符串,可以使用 `printf` 函数结合格式化字符串来实现。
需要注意的是,中文字符在不同的编码下占用的字节数可能不同,因此需要根据实际情况选择相应的格式化字符串。如果中文字符采用 UTF-8 编码,则可以使用 `%s` 格式化字符串;如果中文字符采用 GBK 或 GB2312 编码,则可以使用 `%s` 或 `%S` 格式化字符串。
下面是一个示例代码,用于输出一个 UTF-8 编码的中文字符串:
```c++
#include <cstdio>
#include <string>
int main() {
std::string str = "你好,世界!";
printf("%s\n", str.c_str());
return 0;
}
```
输出结果为:
```
你好,世界!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)