我写了这段代码。在这个程序中,我读取了一个文件,然后将部分文件注入char * temp。最后在文件中写入char * temp。我遇到了一个问题。 当我在文件写入温度只有4个字符写入它,我该怎么办?为什么写功能无法正常工作?
fstream file;
file.open("mary.txt",ios::in);
file.seekg(-1,ios::end);
int pos=file.tellg();
char ch;
char c;
int i=0;
char * temp=new char[100];
file.seekg(0,ios::beg);
while(pos >=0)
{
file.read(&ch,sizeof(char));
if(ch=='a'||ch=='o'||ch=='u'||ch=='e'||ch=='i'||ch=='A'||ch=='O'||ch=='U'||ch=='E'||ch=='I')
{
pos--;
continue;
}
else if(ch>='a' && ch<='z')
{
c=ch-32;
temp[i]=c;
i++;
}
else
{
temp[i]=ch;
i++;
}
pos--;
}
temp[i]=NULL;
cout<<temp<<endl;
cout<<" sizeof temp:"<<sizeof(temp)<<endl;//out put is 4 while temp has longer size!! why?
fstream f("test.txt",ios::trunc);
f.write(temp,sizeof(temp));//if the file contains "abcdeifjle" only written "abcd"
使用'strlen(temp)',而不是'sizeof(temp)' –
'sizeof(temp)'给出指针变量的大小,似乎是当前环境(32位)的4个字节。 –
使用strlen而不是sizeof,也不要忘记在最后调用flush和close方法。 –