【发布时间】:2018-10-23 14:21:26
【问题描述】:
所以我写了一个代码,输入一个单词,把它的第一个字母放在单词的末尾(例如,“egg”将是“gge”,如果我们再次执行相同的过程,它将是“ geg”,然后最后回到“egg”) 我只想执行此过程 1 次。而我想用一个指针来记忆单词的初值,也就是egg,然后字符串要记忆“gge”。
这是代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[100],aux,*P;
int p=1,i,n,k,j;
cin.get(s,100);
i=0;
while(i>=0)
{
P=s; //this is the pointer that SHOULD memorize "egg"
aux=s[0];
for(j=1; j<=n; j++) s[j-1]=s[j];
s[n]=aux;//until here it does the letter thing
break;
}
cout<<P<<endl<<s;//now here the pointer P should be "egg" and the string s should be "gge"
//but the program prints out "gge" and "gge".
return 0;
}
我做错了什么,我应该如何做我想做的事?
【问题讨论】:
-
我比较容易理解。但是如果你知道如何在没有指针的情况下解决这个问题,那还是可以的。
-
显然你更难理解,因为它是错误的;)
-
P除了你指向的char之外什么都不记得。它指向s。它不保留当时的s的值,它始终指向当前的s。 -
@PaulP1 在标准库中有一个旋转算法。
-
不要忘记将
n设置为实际值。
标签: c++ string algorithm pointers