簡體   English   中英

在數組中存儲整數和char

[英]storing integer and char in an array

目標: - 如下圖所示打印A3B5 .. AAABBBBB

我通過以下代碼實現了這一目標: -

#include <stdio.h>
#include <conio.h>

void main(){

    char char1[2],*ptr_char,c;
    int  number[2],*ptr_number,i,j=0,k=0;

    ptr_char = char1;
    ptr_number = number;

    printf("Enter character string\n");
    for(i=0;i<2;i++)
        scanf("%c",&char1[i]);

    printf("Enter number array\n");
    for(i=0;i<2;i++)
        scanf("%d",&number[i]);

    for(i=0;i<ptr_number[j];i++)
        printf("%c",ptr_char[k]);

    j++;
    k++;

    for(i=0;i<ptr_number[j];i++)
        printf("%c",ptr_char[k]);

    getch();
}

///////////////////////////////////////////////////////////

現在我必須采用一個陣列,其中我的A3B5可以采取而不是采取兩個陣列。

但我無法像那樣采取陣列。

我想把A3B5放在單陣列中。 這可能嗎?

你可以說:

char csrc[]= "A3B5" ;

這里的問題是3和5不是數字,它們是字符。 所以你必須從“3”轉換為3.你有幾個選擇,包括sscanfatoi 正如其他人所建議的那樣,立即讀入整個字符串,它將在char數組中,然后將其分解為您想要的單獨部分。

檢查此代碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        int count = 0, i = 0;
        char temp = 0;
        char ip[16] = {0};
        char filter[8] = {0};
        int num[8] = {0};
        printf("Enter input :\t");
        scanf("%s", ip);
        for (count = 0, i =0; count < strlen(ip); count++, i++)
        {
                filter[i] = ip[count];            //take out the character to print
                count++;
                temp = ip[count];                 //read the number of print iteration as a character
                num[i] = atoi(&temp);             // convert "n" [charater] to n [int]
        }
        for (count = 0; count < strlen(ip)/2 ; count++)
        {                                             //print loop
                for (i = 0; i < num[count]; i++)
                        printf("%c\t", filter[count]);
                printf("\n\n");
        }
        return 0;
}

樣品運行和o / p

[sourav@localhost test]$ ./a.out 
Enter input :   S2G5
S   S   
G   G   G   G   G   
[sourav@localhost test]$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM