2014年3月24日月曜日

開発環境

C++実践プログラミング (スティーブ オウアルライン (著)、Steve Oualline (原著)、Steve Oualline(原著)、望月 康司(翻訳)、クイープ(翻訳) 、オライリー・ジャパン)のⅢ部(高度な型とクラス)の15章(シンプルなポインタ)、15.7(プログラミング実習)、実習 15-2を解いてみる。

その他参考書籍

実習 15-2

コード(BBEdit, Emacs)

sample267_2.cpp

#include <iostream>

char *first_char(char s[])
{
  char *c_ptr;

  c_ptr = s;

  while (*c_ptr != '\0' && *c_ptr == ' ')
    ++c_ptr;

  if (*c_ptr == '\0') {
    std::cerr << "Error: Unable to find whitespace in '" << s << "'\n";
    exit (8);
  }
  return c_ptr;
}

int main(int argc, char *argv[])
{
  char line[80];
  char *c_ptr;
  
  std::cout << "Enter string\n";

  std::cin.getline(line, sizeof(line));
  std::cout << '\'' << line << '\'' << '\n';
  
  c_ptr = first_char(line);

  long a = reinterpret_cast<long>(line);
  long b = reinterpret_cast<long>(c_ptr);

  std::cout << std::hex;
  std::cout << a << '\n';
  std::cout << c_ptr[0] << ": " << b << '\n';
  std::cout << std::dec;
  std::cout << a << '\n';
  std::cout << b << '\n';
  return (0);
}

Makefile

#
# FSFのg++コンパイラ用のMakefile
#
CC=g++
CFLAGS=-g -Wall
all: sample267_2

sample267_2: sample267_2.cpp
 ${CC} ${CFLAGS} -o sample267_2 sample267_2.cpp

clean:
 rm sample267_2

入出力結果(Terminal)

$ make && ./sample267_2
g++ -g -Wall -o sample267_2 sample267_2.cppEnter string

''
Error: Unable to find whitespace in ''
$ ./sample267_2
Enter string
 
' '
Error: Unable to find whitespace in ' '
$ ./sample267_2
Enter string
  
'  '
Error: Unable to find whitespace in '  '
$ ./sample267_2
Enter string
c
'c'
7fff5eadab10
c: 7fff5eadab10
140734781827856
140734781827856
$ ./sample267_2
Enter string
c 
'c '
7fff59579b10
c: 7fff59579b10
140734692301584
140734692301584
$ ./sample267_2
Enter string
 c
' c'
7fff5dabdb10
c: 7fff5dabdb11
140734764931856
140734764931857
$ ./sample267_2
Enter string
Hello World!
'Hello World!'
7fff5224eb10
H: 7fff5224eb10
140734571539216
140734571539216
$ Hello World!
bash: Hello: command not found
$ ./sample267_2
Enter string
     Hello World!
'     Hello World!'
7fff4ffffb10
H: 7fff4ffffb15
140734535564048
140734535564053
$

0 コメント:

コメントを投稿