为何使用setw输出时you.date前空格过多导致排版异常?
C++ setw格式化输出排版异常:date字段前多余空格导致错位的解决方法
问题根源
输入处理时的缓冲区残留换行符导致字符串变量赋值完全错位:
- 使用
cin>>you.policy读取数字后,输入缓冲区会留下用户按下的回车键(\n)。 - 紧接着调用
getline(cin, you.date)会直接读取这个残留的换行符,导致you.date被设为空字符串。 - 后续多余的
cin.ignore()和getline(cin,dummy)进一步打乱输入顺序,使得各字段实际值错位,最终输出时空you.date被setw(13)填充大量空格,挤占其他字段空间。
修正后的代码
#include <iostream> #include <cstring> #include <iomanip> #include <cmath> using namespace std; int main() { struct customerinfo { int policy; string date; string loc; string state; string region; double ivalue; string cons; string btype; char earth; char flood; }; customerinfo you; cout<<"Enter your 8-digit policy number: "; cin>>you.policy; cin.ignore(); // 清除cin>>留下的换行符 cout<<"Enter your account expiry date [MM/DD/YYYY]: "; getline(cin,you.date); cout<<"Enter your location [Urban or Rural]: "; getline(cin,you.loc); cout<<"Enter your current residing state: "; getline(cin,you.state); cout<<"Enter your current residing region: "; cin>>you.region; cin.ignore(); // 清除cin>>留下的换行符 cout<<"Enter property value: "; cin>>you.ivalue; cin.ignore(); // 清除cin>>留下的换行符 cout<<"Enter property construction type: "; getline(cin,you.cons); cout<<"Enter your business type: "; getline(cin,you.btype); cout<<"Is earthquake coverage included? [Y or N]: "; cin>>you.earth; cout<<"Is flood coverage included? [Y or N]: "; cin>>you.flood; system("CLS"); cout<<setw(11)<<"Policy #"<<setw(13)<<"Expiry Date"<<setw(11)<<"Location"<<setw(8)<<"State"<<setw(9)<<"Region"<<setw(16)<<"Insured Value"<<setw(14)<<"Const. Type"<<setw(10)<<"B. Type"<<setw(13)<<"Earthquake"<<setw(8)<<"Flood"<<endl; cout<<"---------------------------------------------------------------------------------------------------------------------"<<endl; cout<<setw(11)<<you.policy<<setw(13)<<you.date<<setw(11)<<you.loc<<setw(8)<<you.state<<setw(9)<<you.region<<setw(16)<<you.ivalue<<setw(14)<<you.cons<<setw(10)<<you.btype<<setw(13)<<you.earth<<setw(8)<<you.flood<<endl; }
关键修正点
- 清除cin>>后的换行符:每次用
cin>>读取非字符串类型(int、double、char)后,调用cin.ignore()清除缓冲区残留的换行符,避免后续getline读取空内容。 - 移除冗余输入操作:删除原代码中无意义的
cin.ignore()和getline(cin,dummy),这些操作会破坏输入流顺序,导致变量赋值错位。 - 统一输入逻辑:字符串类型用
getline读取,非字符串类型用cin>>,并在cin>>后及时处理换行符。
内容的提问来源于stack exchange,提问作者Gabriel Lim
相关产品推荐
相关产品推荐

