【问题标题】:How does the setw algorithm works?setw 算法是如何工作的?
【发布时间】:2022-07-02 16:49:22
【问题描述】:

我在想setw 算法(空间计数) 是如何工作的。例如,当有 1 个\t 时,我想用四个空格打印a,我使用\t 并将\tsetw 进行比较。

我写的代码:

# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t"<<"a\n";
std::cout<<std::setw(9)<<"a\n";
return 0;
}

输出

    a // This is 1 '\t'
    a // This is setw()

所以我认为是这样的:

setw(18) = \t\t

听起来合乎逻辑吧?但是当我尝试这段代码时:

# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a";
return 0;
}

它给了我这个输出:

       a
        a

怎么了?

【问题讨论】:

    标签: c++ setw


    【解决方案1】:

    那是因为您需要在setw(18) 处添加\n这适用于任何setw

    示例代码:

    # include <iostream>
    # include <iomanip>
    int main()
    {
    std::cout<<"\t\t"<<"a\n";
    std::cout<<std::setw(18)<<"a\n"; // And you add the \n here
    return 0;
    }
    

    输出:

            a
            a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-04
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多