#include <stdio.h>
#include <ctype.h>
int main( void )
{
int ch;
for ( ch = 0; ch <= 127; ch++ ) {
if ( isprint( ch ) != 0 ) {
if ( isalnum( ch ) != 0 ) {
printf( "%c", ch );
}
else {
printf( "[%c]", ch );
}
}
}
return 0;
}
#include <stdio.h>
#include <ctype.h>
int main( void )
{
char str[] = "AbcDefGHijk1234lmNOP";
int i;
i = 0;
while ( str[i] != '\0' ) {
str[i] = toupper( str[i] );
i++;
}
printf( "str = %s\n", str );
return 0;
}
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[128];
long x = 0;
int i = 0;
printf( "16進数を入力:" );
scanf( "%s", str );
/* データ変換処理 */
while ( str[i] != '\0' ) {
/* 16進数で表せる文字か */
if ( isxdigit(str[i]) != 0 ) {
/* 数字で表せる文字か */
if( isdigit(str[i]) != 0 ) {
/* 10進数に変換 */
x = x * 16 + str[i] - '0';
}
else {
/* 大文字は小文字にしておく */
str[i] = tolower( str[i] );
/* 10進数に変換 */
x = x * 16 + str[i] - 'a' + 10;
}
}
else {
printf( "10進数には変換できません\n" );
return 0;
}
i++;
}
printf( "10進数:%ld\n", x );
return 0;
}
--------------------------------------------------------
※ この問題は、strtolを用いると次のように書き替えが可能です。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[128];
long x = 0;
printf( "16進数を入力:" );
scanf( "%s", str );
/* データ変換処理 */
x = strtol(str, NULL, 16);
printf( "10進数:%ld\n", x );
return 0;
}
--------------------------------------------------------
※ また、sscanfを用いると次のようになります。
#include <stdio.h>
int main(void)
{
char str[128];
long x = 0;
printf( "16進数を入力:" );
scanf( "%s", str );
/* データ変換処理 */
sscanf( str, "%x", &x );
printf( "10進数:%ld\n", x );
return 0;
}
▼戻る▼
「初心者のためのポイント学習C言語」 Copyright(c) 2000-2004 TOMOJI All Rights Reserved