【奇技淫巧】用字符串表示数组

c++将整数转化为字符串有多种实现方法,通常是自己手动实现,也可以用stringstream,atoi,sprintf。但是我最近发现了一个用字符串表示数组的方法,赶紧来告诉大家

先来复习下整数和字符串的转化

 

头文件<stdlib.h>

atoi:字符串 - > 整数

#include <stdio.h>
#include <iostream>
#include <cstdlib> using namespace std; int main(int argc, char **argv) { char s[] = "123"; int n = atoi(s); cout<<n; }

 

sscanf:字符串 - > 整数

#include <stdio.h>
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
    char s[20] = "123";
    int n;
    sscanf(s, "%d", &n);
    cout<<n;
    return 0;
}

 

sprintf:整数 - > 字符串

#include <stdio.h>
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
    int n = 123;
    char s[20];
    sprintf(s, "%d", n);
    puts(s);
}

 

 

字符串 - > 数组(敲黑板)

比如求任意三个数的和:

#include <stdio.h>
#include <iostream>
using namespace std;
int sum(int a[])
{
    int s = 0;
    for(int i = 0; i < 3; i++)
        s += a[i];
    return s;
}
int main(int argc, char **argv)
{
    char s[20];
    for(int i = 0; i < 3; i++)
    {
        scanf("%d", (int*)&s[i*4]);
    }
    cout<<sum((int*)s);
}

用到了强制类型转换,将数存在字符串中,只不过一个数占4个字节,对应4个字符位置。

原文链接: https://www.cnblogs.com/lesroad/p/9508451.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    【奇技淫巧】用字符串表示数组

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/279742

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午4:23
下一篇 2023年2月15日 上午4:25

相关推荐