0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C言語】atoi()で文字列をぶち込んだらint 0の出力になる?例外処理について

Last updated at Posted at 2022-06-07

0で返ってくるのは"0"だけではない。

0で返ってくるけど、元の場合が違う〜といったことがありました。

関数: atoi()
原因: 有効でない文字列を変換しようとすると0を返し、それ以降変換を行わないため

気づいたコーディング状況

数字で入力されているであろう文字入力をint型にしようとして int n = atoi(argv[1]);を用い、その後nの値を見て例外処理をしようとしていた。atoi() には例外処理がなく、数字以外のものを変換しようとすると0を返すことを忘れてしまっていた。どういうことかと言うと、0,1,2,3,4等は0,1,2,3,4で返ってくるが、0,Aは同じ0,0で返ってきてしまうということである。よって暫定的にASCIIコードを用いて入力判定を実装した。

atoi()の例外処理

atoi()には例外処理がない。if((*argv[1]-'0')!= 0 && n==0) この部分で、変換文字列の先頭文字が0ではないのに、変換後に0となっている時にエラーを出すコードを記述した。つまり、有効でない文字列で変換後0となってしまう例外を処理している。

atoi()の例外処理
    int n = atoi(argv[1]);
    if((*argv[1]-'0')!= 0 && n==0){
        //先頭文字が0でないのに、atoiで0
        printf("引数が数字でありません(error)\n");
        exit(1);
    }
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?