C++新手求助:输入输出格式异常问题排查与解决
C++输入输出格式问题解决
问题分析
你的代码核心问题是滥用cin.ignore(),直接导致输入内容丢失、输出排版混乱:
- 程序启动后的第一个
cin.ignore()会吃掉你输入电影名的首字符,所以最终输出的电影名缺失了第一个字母 - 在
cin >>读取整数前加cin.ignore(),会错误处理缓冲区中的字符或换行,造成输出前出现多余空格 cin >>读取整数后,缓冲区残留的换行符不会影响后续cin >>操作,完全不需要额外忽略
修正后的代码
#include <iostream> #include <string> using namespace std; int main() { string movie_name; string lines = "-------------------------------"; int adult_ticket_sold, child_ticket_sold; double gross_profit, theater_gross_profit, distributor_gross_profit; const float adult_ticket_price = 20; const float child_ticket_price = 10; const double theater_income_rate = .4; const double distributor_income_rate = .6; cout << "Project 1\n"; cout << "Written by: billy bill\n"; cout << lines << endl; cout << "Box Office Entry\n"; cout << lines << endl; // 移除多余的cin.ignore(),直接读取完整电影名 cout << "Enter the name of the movie: "; getline(cin, movie_name); // 读取整数前无需cin.ignore() cout << "Enter the amount of adult tickets sold: "; cin >> adult_ticket_sold; cout << "Enter the amount of children tickets sold: "; cin >> child_ticket_sold; gross_profit = (adult_ticket_sold * adult_ticket_price) + (child_ticket_sold * child_ticket_price); theater_gross_profit = theater_income_rate * gross_profit; // 复用已计算的gross_profit,减少冗余 distributor_gross_profit = distributor_income_rate * gross_profit; cout << lines << endl; cout << "Summary: Movie Income Distribution\n"; cout << lines << endl; cout << "The movie: " << movie_name << endl; // 添加空格优化排版 cout << "This is how much the theater made: " << theater_gross_profit << endl; cout << "The distributor gross profit is: " << distributor_gross_profit << endl; cout << lines << endl; cout << "End of Project 1"; return 0; }
关键修改说明
- 删掉所有不必要的
cin.ignore():只有当cin >>读取数据后,紧接着要用getline读取整行内容时,才需要用cin.ignore()清除缓冲区的换行符 - 优化利润计算逻辑,直接复用已算出的
gross_profit,避免重复计算 - 输出电影名时添加空格,让排版更整齐
修正后预期输出
Project 1 Written by: billy bill ------------------------------- Box Office Entry ------------------------------- Enter the name of the movie: the boy that lived Enter the amount of adult tickets sold: 10 Enter the amount of children tickets sold: 10 ------------------------------- Summary: Movie Income Distribution ------------------------------- The movie: the boy that lived This is how much the theater made: 40 The distributor gross profit is: 60 ------------------------------- End of Project 1
内容的提问来源于stack exchange,提问作者Uzuki Z
相关产品推荐
相关产品推荐

