1
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 5 years have passed since last update.

QString を atoi する

Last updated at Posted at 2016-06-29

toInt() を使おう

QString は格納している文字を整数化する toInt() メソッドを持ちます。
特別な理由がない限り、toInt()メソッドで代替できます。

toInt と atoi の違い

toInt() は、文字列を整数化できる場合に、文字列を整数にします。
atoi() は、文字列を前方から整数化できる場合に、該当箇所を文字列を整数にします。

// toInt()
qDebug() << QString("123").toInt() // 123
qDebug() << QString("1b3").toInt() // 0
qDebug() << QString("abc").toInt() // 0
// atoi
qDebug() << atoi("123") // 123
qDebug() << atoi("1b3") // 1
qDebug() << atoi("abc") // 0

atoi する

なんかしらatoiを使う理由がある場合(従来コードでatoiされてるが、実装意図がわからない など)、以下のように const char * を取り出すことで利用できます。

QString str("1b3");
int n = atoi( str.toAscii().constData() ); // n == 1

なお蛇足ですが、atof、atolも同様に応用できます。

参考

C言語 atoi

1
1
0

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
1
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?