MST
星途 面试题库

面试题:C++中字符串格式化输出的常用方法

请描述在C++中,如何使用`<iostream>`库和`<iomanip>`库实现字符串的格式化输出,例如设置浮点数的精度、宽度,以及对齐方式等。并给出相应的代码示例。
28.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

在C++中,通过<iostream>库进行基本的输入输出操作,利用<iomanip>库实现格式化输出。以下是相关操作及代码示例:

  1. 设置浮点数精度: 使用setprecision(n)函数,n为想要设置的精度。

  2. 设置宽度: 使用setw(n)函数,n为想要设置的宽度。

  3. 设置对齐方式

  • left:左对齐
  • right:右对齐
  • internal:符号左对齐,数值右对齐
#include <iostream>
#include <iomanip>
#include <string>

int main() {
    double num = 123.456789;
    std::string str = "Hello, World!";

    // 设置浮点数精度为4
    std::cout << std::setprecision(4) << num << std::endl;

    // 设置宽度为10,右对齐
    std::cout << std::setw(10) << num << std::endl;

    // 设置宽度为15,左对齐
    std::cout << std::left << std::setw(15) << str << std::endl;

    // 设置宽度为15,右对齐
    std::cout << std::right << std::setw(15) << str << std::endl;

    // 设置宽度为15,符号左对齐,数值右对齐(对于浮点数)
    double negativeNum = -123.456;
    std::cout << std::internal << std::setw(15) << negativeNum << std::endl;

    return 0;
}

上述代码展示了如何使用<iomanip>库中的函数来对浮点数和字符串进行格式化输出,设置精度、宽度和对齐方式。