簡體   English   中英

如何在 C 中連接數組中的字符

[英]How to concatenate characters in an array in C

我想從鍵盤獲取一個值(1、2 或 3 位數字),並想在控制台上打印出該值。

我有,

char val[i] // value from a Keypad from 1 through 120
            // so, val[i] could be one, two or three digit number.

我想做的是,

if (val[i] == 1)
    printf("The number you got is %d", val[i]); // prints "The number you got is 1"
else if ((val[i] == 2)
    printf("The number you got is %d", val[i]); // prints "The number you got is 2"
    .
    .
else if ((val[i] == 10)
    printf("The number you got is %d", val[i]); // prints"The number you got is 10"
    .
    .
else if ((val[i] == 120)
    printf("The number you got is %d", val[i]); // prints"The number you got is 108"
else    printf("Error!");               // prints "Error!"

請幫我。 預先感謝您的幫助。

它應該可以正常工作


#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int isNumber(char* s)
{
    for (int i = 0; i < strlen(s); i++)
        if (isdigit(s[i]) == 0)
            return 0;

    return 1;
}

int main()
{
    char * a = (char*) malloc(4);
    scanf("%s",a);

    int i = atoi(a);

    if(isNumber(a) && i>= 1 && i <= 120)
    {
        printf("The number you got is %d\n", i);
    } else printf("Error!");
}

在我的機器上:

輸入:120

Output:你得到的數字是120

輸入:12A

Output:錯誤!

你可以試試下面的代碼

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

int main(){
int num;
int state;
int a,b,data[num];
string element[2];

cout<<"Enter amount data: ";
    cin>>num;
for(a=0;a<num;a++){
    cout<<"Enter state: ";
        cin>>state;

        if(state==3){
            element[0]="A";
        } else if(state==10){
            element[1]="B";
        }   
   }

}

暫無
暫無

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

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