C语言 我试着把一个数组的一个字母转换成一个字母,每个字母,但是它却创造了一个无限循环,我该怎么修复它呢?

edqdpe6u  于 2022-12-11  发布在  其他
关注(0)|答案(1)|浏览(136)

基本上,我试图将数组的每个字母转换为数字,这也是一个数组,但试图用for和ascii来做,这是一个无限循环,你能帮忙吗?
我创建了一个for用变量“I”直到它的字母数组长度,并试图把它的字符数组类型char转换成一个int数数组,但它不能正常工作。

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char teste();
int main(int argc, char *argv[]) {
// inicializing variables
int i = 0, i2 = 0;
char b[]={};
int numero[] = {};
// reads its array "b"
scanf("%s",b);
// and writes it
printf("%s\n",b);
// writes the number which each letter of the array corresponds (What I wanted)
printf("%i", string_tamanho( b));
    for(i = 1; i<= string_tamanho(b); i++){
    numero[i] = b[i] - 96;
    printf("%i\t", numero[i]);
    }

}
int string_tamanho(char b[]) {
    // initializing conta variable (stores the length of the string)
    int conta; 
    
    // incrementing the count till the end of the string
    for (conta = 0; b[conta] != '\0'; ++conta);
    
    // returning the character count of the string
    return conta; 
}
wkyowqbh

wkyowqbh1#

试试这个,我稍微清理了一下代码(让你继续前进),其中string_tamanho中的for循环迭代MAX_STR的次数。

#include <stdio.h>
#include <stdlib.h>
#define MAX_STR 33;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char teste();
int main(int argc, char *argv[]) {
// inicializing variables
int err;
int len=0;
char b[MAX_STR];
int numero[MAX_STR];
b[32]=0;
numero[32]=0;

// prompt for sequence of numbers, read this 
//  https://stackoverflow.com/questions/18372421/scanf-is-not-waiting-for-user-input
err =scanf("%s",b);

// and writes it
//  printf("%s\n",b);

// writes the number which each letter of the array corresponds (What I wanted)
len = string_tamanho(b);
printf("Length b>> %d", len );
    for(int i = 1; i< len; i++){
       numero[i] = b[i] - 96;
       printf("%d\t", numero[i]);
    }

}
int string_tamanho(char b[]) {
    // initializing conta variable (stores the length of the string)
    int conta=0;   
    
    // incrementing the count till the end of the string
    for (conta = 0; (b[conta] != '\0' && conta < MAX_STR); ++conta);
    
    // returning the character count of the string
    return conta; 
}

相关问题