字符串函数的问题(带源码)
我想在一个字符串前面和后面各增加一个字符,使用strcat函数,但是不知道怎么搞的,要增加的后面那个字符不知怎么的就变了?
真的很奇怪!
源码如下:(只是一个函数。)
long jfc(char *p)
{
cout<<"The p is:"<<p<<"\n";
char *begin;char *end;
begin="+";end=";";
long result=1;
\\int temp;temp=p[0];cout<<"Zi Mu is:"<<p[0]<<"\n"<<"ASCII="<<temp<<"\n";
if (p[0]>=48&&p[0]<=57) strcat(begin,p);//我看的BC3.1的帮助,说strcat是使begin和p连起来,返回到begin。
p=begin;
cout<<"The p with Begin is"<<p<<"\n";
cout<<"The begin is"<<begin<<"\n";
cout<<"The end is"<<end<<"\n";//到此为止,我的程序还没有和end发生任何关系,但是end的值已经变了?!
strcat(p,end);
cout<<"The full P is"<<p<<"\n";
cout<<"The begin is"<<begin<<"\n";
cout<<"The end is"<<end<<"\n";
}
问题点数:0、回复次数:7Top
1 楼qhgary(Gary)回复于 2003-02-04 15:45:15 得分 0
是不是begin要分配较多的空间呢,我不知道strcat函数有没有重新分配空间的功能(当他的连接的2个字符串的长度大于第一个字符串指针所能指向的最大空间的时候。
你最好查仔细一点,如果不行,你试试多分配点空间给他们Top
2 楼idler(告别teenage)(偶是豆子。。。)(歇业休息。。。)回复于 2003-02-04 15:57:46 得分 0
完完全全地错了。
首先,要保证begin、p指向的字符数组足够大,否则后果难以预料。(No overflow checking is performed when strings are copied or appended. The behavior of strcat is undefined if the source and destination strings overlap.)
Top
3 楼idler(告别teenage)(偶是豆子。。。)(歇业休息。。。)回复于 2003-02-04 16:07:10 得分 0
帮你修改了一下。
#include <ctype.h>
#include <string.h>
#include <iostream>
#define MAX_SIZE 1024
using namespace std;
long jfc(char *p)
{
char begin[MAX_SIZE]; // 保证足够大
char end[MAX_SIZE];
long result = 1;
strcpy(begin, "+");
strcpy(end, ";");
cout << "The p is: " << p << endl;
if (isdigit(p[0])) // 不应该用if (p[0]>=48&&p[0]<=57),尽量使用标准函数
strcat(begin, p);
p = begin; // 不提倡,丢失了一个指针,但这里不会引起内存泄漏。
cout << "The p with Begin is: " << p << endl;
cout << "The begin is: " << begin << endl;
cout << "The end is: " << end << endl;
strcat(p, end); // 此时begin == p
cout << "The full P is: " << p << endl;
cout << "The begin is: " << begin << endl;
cout << "The end is: " << end << endl;
}
int main()
{
char p[] = "Hello, world!";
jfc(p);
return 0;
}Top
4 楼allen1981813(Nahe des Geliebten)回复于 2003-02-04 21:35:07 得分 0
看看哦Top
5 楼allen1981813(Nahe des Geliebten)回复于 2003-02-04 21:50:55 得分 0
#include <iostream>
#include <cstring>
using namespace std;
void main(){
char *str=new char[225]; //C style string
cout<<"Input:";
cin>>str;
cout<<"Input appendix:";
char *appendix=new char[225]; //C style string
cin>>appendix; //append to back
cout<<"Input ahead:";
char *head=new char[225]; //C style string
cin>>head; //insert to head
strcpy(str,strcat(head,strcat(str,appendix)));//connect all
cout<<"Answer="<<str<<endl;
delete str;
delete appendix;
delete head;
}Top
6 楼freasy(崔沙)回复于 2003-02-05 16:36:02 得分 0
其实不是空间大不大的问题
你犯了一个非常严重的错,这个错误是在c的初学者中经常见到的。
首先,char *begin;char *end;
然后,begin="+";end=";";
问题出来了,你把+\0给了begin,系统报警,你不管,生成的程序只把+的ascii码给了begin,begin指向一个未知区域,不是你的+。end也一样。Top
7 楼myasone([PoLaR!S] KsN!L!)回复于 2003-02-06 10:42:23 得分 0
你忘记了指针的复引用需要有*才行啊
*begin="+"才行Top




