以下程序(是变长输入的字符串)运行正常(在Vsiual Stdio 2005 中编译运行,操作系统是:windows2000):而将有注释的一句移到while大括号外运行时出错。(本意是修改重复的赋值)。请高手指点这是为什么?
#include <iostream>
#include <cstring>
const int N=5;
int main()
{
char *s=new char[N];
char ch;
int n=0,j=1;
while(std::cin.get(ch)&&ch!='\n')
{
if(n==j*N-1)
{
char *temp=new char[n+1+N];
strcpy(temp,s);
delete []s;
s=temp;
j++;
}
s[n++]=ch;
s[n]='\0'; //移到下面的大括号外
}
std::cout<<s<<"\n";
delete []s;
return 0;
}
改动后的程序如下:
#include <iostream>
#include <cstring>
const int N=5;
int main()
{
char *s=new char[N];
char ch;
int n=0,j=1;
while(std::cin.get(ch)&&ch!='\n')
{
if(n==j*N-1)
{
char *temp=new char[n+1+N];
strcpy(temp,s);
delete []s;
s=temp;
j++;
}
s[n++]=ch;
}
s[n]='\0'; //移动的语句
std::cout<<s<<"\n";
delete []s;
return 0;
}