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

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个字符位置。

猜你喜欢

转载自www.cnblogs.com/lesroad/p/9508451.html
今日推荐