📄 subject_15332.htm
字号:
<p>
序号:15332 发表者:李 发表日期:2002-09-17 15:28:52
<br>主题:请教各位一个关于插入字符的问题,困惑很久了.........
<br>内容:如在string的二个字符后插入y,则输出styring <BR>插入字符后,却输出一个乱码,不知为何?<BR>#include<iostream.h> <BR>#include<string.h><BR>void main() <BR>{<BR>int i;<BR>char ch,*s="string";; <BR>char *p=new char[strlen(s)+1];<BR>cin>>i;<BR>cout<<"在"<<i<<"处插入字符”"<<endl; <BR>if(i>(strlen(s)+1))<BR>cout<<"error"<<endl; <BR>else <BR>cout<<"input ch:"<<endl; <BR>cin>>ch; <BR>strncpy(p,s,i); <BR>for(int n=i+1;n<=strlen(s)+1;n++) <BR>{ <BR>*(p+n+1)=*(s+n); <BR>} <BR>*(p+i+1)=ch; <BR>cout<<p<<endl; <BR>delete[] p; <BR>}
<br><a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p>
<hr size=1>
<blockquote><p>
<font color=red>答案被接受</font><br>回复者:xiongli 回复日期:2002-09-17 16:24:48
<br>内容:你中间的循环有错误,最后delete[] p 的时候,释放了不该释放的内存,所以会崩溃。<BR><BR>#include<iostream.h> <BR>#include<string.h><BR>void main() <BR>{<BR>int i=2;<BR>char ch='y';<BR>char *s="string";<BR>char *p=new char[8];<BR>strncpy(p,s,i); <BR>int x=strlen(s);//x=6<BR>for(int n=i;n<=x;n++) <BR>{ <BR>*(p+n+1)=*(s+n); <BR>} <BR>*(p+i)=ch; <BR>*(p+7)='\0';<BR>cout<<p<<endl; <BR>delete [] p; <BR>} <BR><BR>不完善,调试的时候用的。
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
<hr size=1>
<blockquote><p>
回复者:le_ej 回复日期:2002-09-17 16:35:02
<br>内容:可能与你用new有关<BR>试试这样:<BR>#include<iostream.h><BR>#include<string.h><BR>void insert(char *str,int n,char ch)<BR>{<BR> int i,len = strlen(str)+1;<BR> for(i=len;i>=n;i--) str[i] = str[i-1];<BR> str[i] = ch ; <BR> str[len+1] = '\0';<BR>}<BR>void main(void)<BR>{<BR> int n;//the insert number<BR> char ch,*str="string";<BR> cout<<"input n=";<BR> cin>>n;<BR> cout<<"input ch=";<BR> cin>>ch;<BR> insert(str,n,ch);<BR> cout>>str;<BR>}<BR> <BR>
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
<hr size=1>
<blockquote><p>
回复者:le_ej 回复日期:2002-09-17 16:52:32
<br>内容:我再补充一下:<BR>因为cout<<str中的str字符串必须是以'\0'结束的,<BR>你看到有乱码是因为在str后缺乏'\0'结束符。<BR>加上就可以了。
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
<hr size=1>
<blockquote><p>
回复者:天才 回复日期:2002-09-17 16:53:07
<br>内容:楼上的好像不对<BR>2002-9-17 16:56:01
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -