C/C++ 字符串处理

原文出处:http://www.cnblogs.com/skunk/archive/2009/05/06/1450903.html

把字符串转换成整型数

  函数说明: atoi()会扫描参数nptr字符串,检测到第一个数字或正负符号时开始做类型转换,之后检测到非数字或结束符 \0 时停止转换,返回整型数。
  原型: int atoi(const char *nptr); atof()可以将字符串转为相应的浮点数,自己去逐个字符读取然后计算出字符串对应的浮点数的话平添麻烦,而且有时还不精确(比如字符串2.35,转为浮点数就得经过2+3*0.1+5*0.01的计算。)
  需要用到的头文件: #include <stdlib.h>
  程序例:


  #include <stdlib.h>
  #include <stdio.h>
  int main(void)
  {
  int n;
  char *str = "12345.67";
  n = atoi(str);
  printf("string = %s integer = %d\n", str, n);
  return 0;
  }
  执行结果
  string = 12345.67 integer = 12345

将C++ string的c_str()返回值赋值给char*

c_str函数的返回值是const char*的,不能直接赋值给char*,所以就需要我们进行相应的操作转化(借助strcpy()),下面就是这一转化过程。
程序例:
  #include <iostream>
  #include <string>
  using namespace std;
  void main()
  {
  string add_to="hello!";
  //std::cout<<add_to<<endl;
  const string add_on="baby";
  const char*cfirst = add_to.c_str();
  const char*csecond = add_on.c_str(); 
  char*copy = new char[strlen(cfirst) + strlen(csecond) + 1];
  strcpy( copy, cfirst);
  std::cout<<copy<<endl;
  //strcat( copy, csecond);
  add_to = copy;
  delete [] copy;
  std::cout<<add_to<<std::endl;
  }

猜你喜欢

转载自blog.csdn.net/u013345641/article/details/56666358
今日推荐