在printf(C)中显示字符串而不是数字

时间:2016-10-15 09:27:11

标签: c string int switch-statement printf

我已经用C编写了这个代码,只是在某个数字上显示了一条消息

int main(void) {
int a, d;    
d = scanf("%d", &a);
switch(a){
    case 1:
        printf("ml' nob:\n%d\nQapla'\nnoH QapmeH wo' Qaw'lu'chugh yay chavbe'lu' 'ej wo' choqmeH may' DoHlu'chugh lujbe'lu'.\n", a);
        break;
    case 2:
        printf("ml' nob:\n%d\nQapla'\nQu' buSHa'chugh SuvwI', batlhHa' vangchugh, qoj matlhHa'chugh, pagh ghaH SuvwI''e'.\n",a);
        break;
    case 3:
        printf("ml' nob:\n%d\nQapla'\nqaStaHvIS wa' ram loS SaD Hugh SIjlaH qetbogh loD.\n",a);
        break;
    case 4:
        printf("ml' nob:\n%d\nQapla'\nHa'DIbaH DaSop 'e' DaHechbe'chugh yIHoHQo'.\n",a);
        break;
    case 5:
        printf("ml' nob:\n%d\nQapla'\nleghlaHchu'be'chugh mIn lo'laHbe' taj jej.\n",a);
        break;
    default:
        printf("ml' nob:\n%d\nluj\n", a);
        break;
}
return 0;}

但是当我在输入中输入字符串或字符时,它给了我很多无意义的数字。有没有办法显示我在默认情况下输入的字符串而不是数字。

编辑: 输入

abc

输出

What i want : abc
What it shows: 3469312

1 个答案:

答案 0 :(得分:-1)

试试这个..!

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

#include <stdio.h>
using namespace std;
int main(void) {
    int a, d;
    char str[10];
    scanf("%s", &str);

    char* err = NULL;
    a = strtol(str, &err,10);
    if (err==NULL)  //Conversion Error
        a = -1;

    switch((int)a){
    case 1:
        printf("ml' nob:\n%d\nQapla'\nnoH QapmeH wo' Qaw'lu'chugh yay chavbe'lu' 'ej wo' choqmeH may' DoHlu'chugh lujbe'lu'.\n", a);
        break;
    case 2:
        printf("ml' nob:\n%d\nQapla'\nQu' buSHa'chugh SuvwI', batlhHa' vangchugh, qoj matlhHa'chugh, pagh ghaH SuvwI''e'.\n",a);
        break;
    case 3:
        printf("ml' nob:\n%d\nQapla'\nqaStaHvIS wa' ram loS SaD Hugh SIjlaH qetbogh loD.\n",a);
        break;
    case 4:
        printf("ml' nob:\n%d\nQapla'\nHa'DIbaH DaSop 'e' DaHechbe'chugh yIHoHQo'.\n",a);
        break;
    case 5:
        printf("ml' nob:\n%d\nQapla'\nleghlaHchu'be'chugh mIn lo'laHbe' taj jej.\n",a);
        break;
    default:
        printf("ml' nob:\n%s\nluj\n", str);
        break;
    }
    return 0;}