简体   繁体   English

如何将用户输入的格式设置为整齐的表格,以便在C ++中输出

[英]How can I format user input into a neat table for output in C++

I am having problems with getting this table to line up correctly, this is a cout statement from my table. 我在使该表正确对齐方面遇到问题,这是我的表中的cout语句。 My problem is how can I format different things in one line without it messing up the next entry in the line. 我的问题是如何在一行中设置不同的格式,而又不会弄乱该行中的下一个条目。 For example, when I use setprecision(2) for my goldweight, the goldvalue gets messed up and gives me a weird number like 5656e+02 例如,当我使用setprecision(2)作为我的权重时,goldvalue被弄乱了,并给了我一个奇怪的数字,例如5656e + 02

 cout << "                   Value Analysis" <<endl;
cout << "Gold: " << setw(6) <<  "" <<goldweight<< "  Oz @ "<<costgold<<"
("<<setw(1)<<    ""<<carats<<"         Carats) $"<<goldvalue<<endl;

您需要将其重置为下一个输入,例如,如果您已经设置了精度,则将其重新设置(未设置)

    std::cout.unsetf ( std::ios::floatfield );

Yes, setw() , setprecision() , etc will mess up stuff. 是的, setw()setprecision()等会弄乱东西。 What you can do is to use temporary std::ostringstream . 您可以使用临时std::ostringstream

#include <sstream>
...
std::ostringstream oss_goldweight ;
std::ostringstream oss_goldvalue ;
std::ostringstream oss_goldcarats ;

oss_goldweight << setw(6) << goldweight ;
oss_goldvalue << setprecision(2) << goldvalue ;
oss_goldcarats << setw(1) << carats ;

and then use oss_goldxyz variables instead of raw values. 然后使用oss_goldxyz变量而不是原始值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM