c++ - 程序卡住了,没有打印输出
问题描述
我是 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;
}
这段代码的问题是我想打印 Name[] 数组的全名。但仅在打印“Hello1”后就卡住了。在“Hello1”之后它没有打印任何东西。它正在正确输入所有三个名称(在 First[] 、 Middle[] 和 Last[] 中)。所以,我决定从第 1 行开始追踪我的代码。我知道在第一个 while 循环之后存在一些问题,因为我试图打印“Hello1”和“Hello2”。问题是它正在正确打印“Hello1”,但它却被“Hello2”卡住了。我认为有些问题出在第二个 while 循环中。但我没有收到错误我该如何解决这个问题。
请帮助我解决这个问题,以便它可以正确打印全名。
解决方案
好的,问题是你的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
推荐阅读
- amazon-web-services - AWS Glue 与 Athena
- javascript - 对象值替换现有对象值 - Javascript
- excel - 如果过滤条件不存在,请勿将过滤器应用于列
- html - 我的 .css 文件在我的 .html 文件中不起作用
- php - curl - 在邮递员中测试的数据在 php 代码中不起作用
- sql-server - 如何克服 SQL Server 对“IN”查询参数计数的限制?
- php - Laravel:仅在预生产时违反完整性约束
- azure-app-configuration - 从 Azure 应用配置中选择标记值和未标记值
- python - 在 python 中,如何修复列表索引超出范围的问题?
- google-cloud-platform - GCE:'未能注册层'