我的任务是接收来自用户的字符串输入并反转字符串的顺序并打印结果。我的代码是这样的:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
string input;
char *head = new char, *tail = new char;
char temp;
//Get the string from the user that will be reversed
cout << "Enter in a string that you want reversed: ";
getline(cin, input);
//Create and copy the string into a character array
char arr[input.length()];
strcpy(arr, input.c_str());
//Set the points of head/tail to the front/back of array, respectably
head = &arr[0]; tail = &arr[input.length()-1];
//Actual reversal part of the code (Does not work)
for(int i=0; i<input.length(); i++) {
temp = *(tail);
*tail = *head;
*head = temp;
tail --; head ++;
}
//Print the character array
for(int i=0; i<input.length(); i++) {
cout << arr[i];
}
//Free up memory
delete head; delete tail;
head = NULL; tail = NULL;
return 0;
}
当我打印它时,实际上没有任何改变,我似乎无法理解为什么,因为我对指针是全新的。这是我遇到问题的特定块:
for(int i=0; i<input.length(); i++) {
temp = *(tail);
*tail = *head;
*head = temp;
tail --; head ++;
}
非常感谢任何有关如何解决此问题或一般指针知识的输入,这将有所帮助。