CC++常用函数

  • 格式:doc
  • 大小:59.50 KB
  • 文档页数:5

pch = strstr (str,"s"); //pch没有开辟新的地址,还是指向str的
地址空间,次例输出可以说明问题
strncpy (pch,"sample",6);
puts (str);
strcpy(st,pch);
cout<<*pch<<endl;//此输出只有一个字符,若想要全部还需要一个
缓冲区
char a[2];
char* b;
a[0]='[';//不能为a[0]="w"; 此为两个字符,还有一个'/0'
a[1]=50;
b=strstr("@@![#$",a);
return 0;
}
/**********************strncpy example***************************/ #include <stdio.h>
#include <string.h>
int main ()
{
char str1[]= "To be or not to be";
char str2[6];
strncpy (str2,str1,5);//将str1前五个字符复值给str2
str2[5]='/0';
puts (str2);
return 0;
}
/************************strcpy_s(VC6.0没有此函数)和
strcpy()****************************/
strcpy_s和strcpy()函数的功能应该一样的。

strcpy函数,就象gets函数一样,它没有方法来保证有效的缓冲区尺寸,所以它只能假定缓冲足够大来容纳要拷贝的字符串。

在程序运行时,这将导致不可预料的行为。

用strcpy_s就可以避免这些不可预料的行为。

这个函数用两个参数、三个参数都可以,只要可以保证缓冲区大小。

三个参数时:
errno_t strcpy_s(
char *strDestination,
size_t numberOfElements,
const char *strSource
);
两个参数时:
errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only
#include<iostream>
#include<string>
using namespace std;
void main()
{
char *str1=NULL;
str1=new char[20];
char str[7];
strcpy_s(str1,20,"hello world");//三个参数
strcpy_s(str,"hello");//两个参数但如果:char *str=new char[7];会出错:提示不支持两个参数
cout<<"strlen(str1)"<<strlen(str1)<<"strlen(str)"<<strlen(str)<<endl; printf(str1);printf("/n");
cout<<str<<endl;
}
1.CString 转换 string
CString str;
GetDlgItem(IDC_EDIT1)->GetWindowText(str);
info.account = str.GetBuffer(0);
str.ReleaseBuffer();
2.CString 转换 char数组
char *p;
char c[10];
p=str.GetBuffer(str.GetLength());
str.ReleaseBuffer();
strcpy(c,p);
3.string to double
10 #include <iostream>
11 #include <string>
12 #include <cstdlib>
13
14using namespace std;
15
16int main() {
17string s = "123";
18double n = atof(s.c_str());
19//int n = atoi(s.c_str());
20
21 cout << n << endl;
22 }
4.Char * 转换string
char* cExpression
string str(cExpression);
5.int转string
string转
char[]
#include <iostream> #include <sstream> #include <string>
using namespace std;
int main()
{
stringstream sstr;
//--------int转string-----------
int a=100;
string str;
sstr<<a;
sstr>>str;
cout<<str<<endl;
//--------string转char[]--------
sstr.clear();//如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。

string name = "colinguan";
char cname[200];
sstr<<name;
sstr>>cname;
cout<<cname;
system("pause");
}。