首页 > 解决方案 > 程序卡住了,没有打印输出

问题描述

我是 C++ 的初学者。我正在尝试在 C++ 中使用字符数组。所以,我写了这段代码。

#include <iostream>

using namespace std;

//Main Function
int main()
{
   //Variable declaration
   char First[30];
   char Middle[30];
   char Last[40];
   //Array to store all names
   char Name[70];

   //Loop variables
   int i = 0, j = 0;

   //Reading all the name
   cout << "Enter First name: ";
   cin >> First;

   cout << "Enter Middle name: ";
   cin >> Middle;

   cout << "Enter Last name: ";
   cin >> Last;

   //Copies all characters of Last name to fourth array
   while (Last[i] != '\0')
   {
       Name[j] = Last[i];
       i++;
       j++;
   }
   //placing a comma in the fourth array and adding a space
   Name[j] = ',';
   j++;
   Name[j] = ' ';
   j++;

    cout<<"Hello1\n";

   //Copies all characters of First name to fourth array
   i = 0;
   while (First[i] != '\0');
   {
       Name[j] = First[i];
       i++;
       j++;
   }
   //Add a space
   Name[j] = ' ';
   j++;


    cout<<"Hello2\n";

   //Copies all characters of Middle name to fourth array
   i = 0;
   while (Middle[i] != '\0');
   {
       Name[j] = Middle[i];
       i++;
       j++;
   }
   Name[j] = '\0';
   //Display the fourth array
   cout << Name << endl;
}

标签: c++

解决方案


好的,问题是你的while循环,你犯了放一个;的错误 最后,这是一个无限循环,永远不会得到第二个你好。

//Copies all characters of First name to fourth array
   i = 0;
   while (First[i] != '\0'); // <- Here is your problem

应该:

//Copies all characters of First name to fourth array
   i = 0;
   while (First[i] != '\0') { // <- Here is your problem

编辑

感谢 Gilles-Philippe Paillé 指出,在第三个 while 循环中还有一个分号,应该删除:D


推荐阅读