問題
文字列sの中に、文字cが含まれていれば、その添え字(文字列中に文字cが複数ある場合は、最も先頭側の添え字とする)を返し、含まれていなければ-1を返す関数を作成せよ。
int str_char(const char s[],int c){/ ・・・/}**
下記は私が考えた、この問題に対するプログラムです。
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int str_char(const char s[], int c) { int i; int len = 0; while (s[len]) len++; for (i = 0; i < len; i++) { if (s[i] == c) return i; } return -1; } int main(void) { char str[128]; int co; printf("文字列を入力してください\n"); scanf("%s", str); printf("文字を入力してください\n"); scanf("%d",&co); printf("文字列の中にある入力した文字の添え字は%d\n", str_char(str, co)); return 0; }
このプログラムを実行すると、int str_char(const char s[],int c){/* ・・・*/}の返却値が必ず-1になってしまいます。
なぜ、if (s[i] == c) return i;としては、いけないのか理由が知りたいです。
よろしくお願いします。
下記は訂正後のコードです
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int str_char(const char s[], int c) { int i; int len = 0; while (s[len]) len++; for (i = 0; i < len; i++) { if (s[i] == c) return i; } return -1; } int main(void) { char str[128]; int a; char co; printf("文字列を入力してください\n"); scanf("%s", str); printf("文字を入力してください\n"); scanf(" %c", &co); a = str_char(str, co); printf("文字列の中にある入力した文字の添え字は%d\n", a); return 0; }
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/25 07:19
2020/02/27 02:14