【发布时间】:2021-09-10 07:26:29
【问题描述】:
所以我编写了这段代码来根据用户选项来反转其中一个名称,想法是使用另一个函数来反转并使用指针,但是在尝试了所有我能想到的代码之后,我的代码返回相同的名称而不是最好的我能做的就是把名字的第一个字母改成一个奇怪的符号。
#include <iostream>
using namespace std;
void reverse(char* A) {
int count = 0;
char temp[10];
for (int i = 0; A[i] != NULL; i++)
count++;
for (int i = 0; A[i] != NULL; i++) {
temp[count]=A[i];
count--;
}
for (int i = 0; A[i] != NULL; i++) {
A[i] = temp[i];
}
}
int main(){
int x= 0;
int index;
char Name_list[5][10];
cout << "please enter the names of the student " << endl;
for (int i = 0; i < 5; i++) {
cin >> Name_list[i];
for (int j = 0; Name_list[i][j] != NULL; j++) {
x++;
}
while (x > 10)
{
x = 0;
cout << "you have entered more then the allowed number of characters per name enter another name " << endl;
cin >> Name_list[i];
for (int j = 0; Name_list[i][j] != NULL; j++) {
x++;
}
}
x = 0;
}
for (int i = 0; i < 5; i++) {
cout << Name_list[i] << endl;
}
cout << "please enter the index of the name you want to reverse" << endl;
cin >> index;
while (index>4||index <0)
{
cout << "you entered incorrect index please enter a number from 0 to 4 " << endl;
}
reverse(Name_list[index]);
for (int i = 0; i < 5; i++) {
cout << Name_list[i] << endl;
}
system("pause");
}
【问题讨论】:
-
您是否尝试过在调试器中跟踪
reverse的每一行? -
调试器很有帮助,但你也可以在纸上做这个。从一个 3 个字母的单词开始,为数组槽画一些框,按照你的逻辑,看看每个字母在哪里结束。
-
这并没有解决问题,但
NULL是一个空指针常量。它不是char值。它可能在这段代码中运行良好,但字符串终止符的正确值为’\0’。 -
@Osama,建议:不使用“char Name_list[5][10];”,可以使用“string Name_List[5]”,然后调用Name_List[i].reverse () 反转名称。
标签: c++ reverse c-strings function-definition