如何在终端程序中调整光标,使其与输出列对齐?

How can I justify my cursor to line up with my output colums in a terminal program?

本文关键字:输出 对齐 光标 终端 程序 调整      更新时间:2023-10-16
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double PI = 3.14159;
double rad = 0;
double area = 0;
double vol = 0;
int areaPi = 0;
int volPi = 0;
cout << setprecision(5) << fixed;
cout << setw(38) << left << "Enter radius for the sphere: " << right);
cin  >> rad;
area = (4 * PI * (rad * rad));
vol = ((4.0/3.0) * PI * (rad * rad * rad));
areaPi = (4 * (rad *rad));
volPi = (4 * (rad * rad * rad));
cout << right << "Surface area of the sphere: " << setw(12) << area << " (" << areaPi << "u03C0)";
cout << "n";
cout << "The volume of the sphere: " << setw(14) << vol << " (" << volPi << "π/3)";
cout << "n";
return 0;
}

你好男人。因此,我遇到的问题是,当您为半径(rad)变量输入一个值时,当用户键入导致双位数比输出列长时,光标希望从左到右工作。

当程序运行时,如果你输入任何大于1位的数字,它看起来是这样的:

//Enter radius for the sphere:           17
//Surface area of the sphere:   3631.67804 (1156π)
//The volume of the sphere:    20579.50889 (19652π/3)

我想让7与它下面的列对齐。我尝试将宽度设置为比之前的宽度小1 &单个数字以左移一个空格结束,如下所示:

//Enter radius for the sphere:          4
//Surface area of the sphere:    201.06176 (64π)
//The volume of the sphere:      268.08235 (256π/3)

我将把输出存储到一组字符串中。然后,您可以根据需要检查和操作数据。或者,您可以在打印

之前计算所需的空格偏移量。
 // convert to string for digit count
std::string output_1 = std::to_string(x);
std::string output_2 = std::to_string(y);
int o_1_2_dist = output_1.size() - output_2.size(); // difference in digits
std::string padding_1, padding_2;
if (o_1_2_dist < 0)
    padding_1 = std::string(abs(o_1_2_dist), ' ');
else
    padding_2 = std::string(o_1_2_dist, ' ');
std::cout << padding_1 << output_1 << 'n' << padding_2 << output_2;

你想要调整一个输出字符串,这样它就不会计算你不关心的数字的额外位。比如output_1 = std::to_string(floor(x));这样就不用数小数

后面的数字了

这可以通过计算输入的长度来解决。我使用c++11的to_string将结果值转换为字符串并找出它们的长度。我还没试过它有多便携。它似乎可以在linux下与gcc 6.1.1一起工作。,但由于某种原因,它不能与输入一起工作,所以我也改变了这部分,以便用户输入std::string,之后转换为双精度。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double PI = 3.14159;
double rad = 0;
double area = 0;
double vol = 0;
int areaPi = 0;
int volPi = 0;
int width_col1 = 40;
//cout.fill('.');
cout << setprecision(5) << fixed;
cout << left << setw(width_col1) << "Enter radius for the sphere: " << right;
std::string input;
cin  >> input;
rad = stod(input);
area = (4 * PI * (rad * rad));
vol = ((4.0/3.0) * PI * (rad * rad * rad));
areaPi = (4 * (rad *rad));
volPi = (4 * (rad * rad * rad));
int indent = width_col1 + input.length() + 1; 
cout << left << setw(indent - to_string(area).length()) << "Surface area of the sphere: " << area << " (" << areaPi << "u03C0)" << std::endl;
cout << left << setw(indent - to_string(vol).length()) << "The volume of the sphere:   " << vol << " (" << volPi << "π/3)" << std::endl;
return 0;
}
  • 这个解决方案类似于C程序员对printf所做的。

  • 我很想知道为什么这对输入不起作用