• 最近遇到的C++数字和字符串的转换问题


    1、

    用itoa 和atoi  在头文件#include<cstidlib>

    itoa用法:

    char *  itoa ( int value, char * str, int base );
    value
    Value to be converted to a string.
    str
    Array in memory where to store the resulting null-terminated string.
    base
    Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.

    其中返回值和str是一样的。

    atoi用法:

    int atoi (const char * str);
    /* atoi example */
    #include <stdio.h>      /* printf, fgets */
    #include <stdlib.h>     /* atoi */
    
    int main ()
    {
      int i;
      char buffer[256];
      printf ("Enter a number: ");
      fgets (buffer, 256, stdin);
      i = atoi (buffer);
      printf ("The value entered is %d. Its double is %d.
    ",i,i*2);
      return 0;
    }

    2、sprintf 在头文件#include<cstdio>

    int sprintf ( char * str, const char * format, ... );
    Return value:
    On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.
    On failure, a negative number is returned.
    /* sprintf example */
    #include <stdio.h>
    
    int main ()
    {
      char buffer [50];
      int n, a=5, b=3;
      n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
      printf ("[%s] is a string %d chars long
    ",buffer,n);
      return 0;
    }

    3、字符串流的使用 

    头文件:#include<sstream>

    stringstream strm;             创建自由的stringstream对象
    stringstream strm(s);              创建存储s的副本的stringstream对象,其中s是string类型的对象
    strm.str();                 返回strm中存储打的string类型对象
    strm.str(s);                将string类型的s复制给strm,返回void
    string line,word;
    while(ginline(cin,line))
    {
         istringstrem strem(line);
         while(strem >> word)
         {
                //do something
          }    
    }

    class istream  可用来读取数据

    class ostream 可用来写出数据

    #include <sstream>
    #include <iostream>
    using namespace std;
    int main ()
    {
     
      int val1=255, val2=587;
      ostringstream format_message;
      format_message << "val1: " << val1 << endl
                       << "val2: " << val2 << endl;
      istringstream input_istring(format_message.str());
      cout << input_istring.str() << endl;
      cout << format_message.str() << endl;
      string dump;
       int val11,val22;
      input_istring >> dump >> val11 >> dump >> val22;
     
      cout << val11 << " " << val22 << endl;
      return 0;
    }
  • 相关阅读:
    beforeRouteLeave 实现vue路由拦截浏览器的需求,进行一系列操作 草稿保存等等
    VUE 路由变化页面数据不刷新问题
    vue 监听 watch 使用
    vue-cli配置文件详解
    vue-cli脚手架中webpack配置基础文件详解
    Dbus组成和原理
    NUMA架构的优缺点
    define 的全部使用方法
    敏捷(Agile)——“说三道四”
    Linux 内核模块编译 Makefile
  • 原文地址:https://www.cnblogs.com/yi-meng/p/3695923.html
Copyright © 2020-2023  润新知