C++使用cout输出时如何让'Additional'对齐到'For $39.99'正下方?
解决方案
你之前的写法达不到效果核心有两个原因:
setw()只对紧随其后的一次输出操作生效,且当待输出内容长度超过setw()指定的宽度时,setw()会直接失效,你给远长于10个字符的整句设置setw(10)自然没有效果- 你需要的是第二行开头填充和第一行前缀
Package A:等长的空格,而不是给第二行的整句设置输出宽度
方法1:直接填充等长空格(最简单)
数清楚第一行前缀Package A: 的长度为11个字符,第二行开头直接输出11个空格即可,示例代码:
#include <iostream> #include <string> // 要使用string构造函数生成空格需要包含这个头文件 using namespace std; int main() { char choice; cout << "Package A: For $39.99 per month, 4 gigabytes are provided.\n" << string(11, ' ') << "Additional data costs $10 per gigabytes."; return 0; }
方法2:动态计算前缀长度(更易维护)
如果后续可能修改前缀内容,不想每次都重新数字符数,可以把前缀抽成常量,自动计算长度生成对应空格:
#include <iostream> #include <string> #include <cstring> using namespace std; int main() { char choice; const char* line_prefix = "Package A: "; cout << line_prefix << "For $39.99 per month, 4 gigabytes are provided.\n" << string(strlen(line_prefix), ' ') << "Additional data costs $10 per gigabytes."; return 0; }
方法3:用setw实现(符合你原来的使用习惯)
如果你还是想用setw实现也可以,给第二行开头的空字符串设置对应宽度即可,注意要加left操纵符让空格补在空字符串右侧:
#include <iostream> #include <iomanip> // 用setw需要包含这个头文件 using namespace std; int main() { char choice; cout << "Package A: For $39.99 per month, 4 gigabytes are provided.\n" << left << setw(11) << "" << "Additional data costs $10 per gigabytes."; return 0; }
内容的提问来源于stack exchange,提问作者mmbkp
相关产品推荐
相关产品推荐

