【问题标题】:how can I print a char array in c++如何在 C++ 中打印 char 数组
【发布时间】:2016-07-11 11:29:50
【问题描述】:

我正在处理一个简单的酒店预订项目,但在输入客户姓名后无法打印客户姓名和付款类型。这是我输入的一段代码。

 cout << "Please enter the customer name: " << endl;
 cin >> customername1;
 cin.getline(customername1,100,'\n');
 fflush(stdin);
 cout << "Please enter the payment type: " << endl;
 cin >> paymenttype;
 cin.getline(paymenttype,100,'\n');
 fflush(stdin);
 cout << "How many days would you like to stay: " << endl;
 cin >> days;
 room_income = days * 30;
 count_room++ ;
 count_customer1++ ;
 customer_name1[single]= new char [strlen(customername1)+1]; 
 strcpy(customer_name1[single],customername1); 
 payment_type[single]= new char [strlen(paymenttype)+1]; 
 strcpy(payment_type[single],paymenttype);
 cout << "Room number : " << single << endl<< endl;
 cout << "Customer name : "<< customer_name1 << endl << endl;
 cout << "Payment type : "<< payment_type << endl<< endl;
 cout << "Number of day for accomodation :"<< days << endl<< endl;
 cout << "Income for this room : "<< room_income<< endl<< endl;

为客户名称和付款类型显示一些随机数字和字母。我怎样才能正确地写它们?

【问题讨论】:

  • say customername1 的类型是什么?为什么要读两遍? (&gt;&gt;getline
  • new char [strlen(customername1)+1]; 哇哦!不如来一场精彩的std::string 游戏?
  • cin &gt;&gt; customername1; 已经读取了输入,你为什么还要cin.getline(customername1,100,'\n');??
  • 是的,你们是对的。问题已解决。 cin.getline(customername1,100,'\n');没用。谢谢。

标签: c++ arrays printing char


【解决方案1】:

对于客户名称和付款类型,您尝试打印数组,而不是一个元素。由于数组基本上只是指向第一个元素的指针,因此您会得到一个“随机数”,即内存地址。

试试:

cout << "Customer name : "<< customername1 << endl << endl;
cout << "Payment type : "<< paymenttype << endl<< endl;

当你完成这项工作时,请按照 cmets 并查看 std::string 和向量...

【讨论】:

  • 是的,你是对的,而且我认为 cin.getline(customername1,100,'\n') 是不必要的
  • @NathanOliver:不,仔细查看变量的名称... OP,您的评论是对的。
  • 好电话。讨厌的小下划线。
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2018-10-23
  • 2016-01-26
  • 1970-01-01
相关资源
最近更新 更多