読者です 読者をやめる 読者になる 読者になる

個人的自由ノート

ふと自分が気になった事を書いてます

C++で問題を解く

#include <iostream>
#include <cstddef>

using namespace std;

int main(void){
  int asize;
  cout << "要素数 : ";
  cin >> asize;

  double* a = new(nothrow) double[asize];

  if(a == NULL){
    cout << "配列の生成に失敗しました。" << endl;
    return 1;
  }

  for(int i = 0; i < asize; i++){
    a[i] = i * 1.1;
  }

  for(int j = 0; j < asize; j++){
    cout << "a[" << j << "] = " << a[j] << endl;
  }

  return 0;
}



#include <iostream>

using namespace std;

void mem_set(void* p, int n, unsigned char v){
  unsigned char* q = static_cast<unsigned char*>(p);
  for(int i = 0; i < n; i++)
    *q++ = v;
}

int main(void){
  int a[4] = {1,2,3,4};
  long b[2] = {1,2};

  cout << "a : "; for(int i = 0; i < 4; i++) cout << a[i] << ' '; cout << endl;
  cout << "b : "; for(int i = 0; i < 2; i++) cout << b[i] << ' '; cout << endl;

  mem_set(a, sizeof(a), 1);
  mem_set(b, sizeof(b), 0);

  cout << "a : "; for(int i = 0; i < 4; i++) cout << a[i] << ' '; cout << endl;
  cout << "b : "; for(int i = 0; i < 2; i++) cout << b[i] << ' '; cout << endl;

  return 0;
}





#include <iostream>
#include <typeinfo>

using namespace std;

int main(void){
  cout << "■文字列リテラル\"ABC\"" << endl;
  cout << " 型:" << typeid("ABC").name()
  << "  大きさ:" << sizeof("ABC") << endl;
  cout << "■文字列リテラル\"\"" << endl;
  cout << " 型:" << typeid("").name()
  << "  大きさ:" << sizeof("") << endl;
  cout << "■文字列リテラル\"ABC\\0DEF\"" << endl;
  cout << " 型:" << typeid("ABC\0DEF").name()
  << "  大きさ:" << sizeof("ABC\0DEF") << endl;

  return 0;
}





#include <iostream>

using namespace std;

int main(void){
  char s1[4] = "ABC";
  char s2[] = "ABC";
  char s3[6] = "ABC";
  char s4[] = "ABC\0DE";

  cout << "配列s1に文字列\"" << s1 << "\"が格納されています。" << endl;
  cout << "配列s2に文字列\"" << s2 << "\"が格納されています。" << endl;
  cout << "配列s3に文字列\"" << s3 << "\"が格納されています。" << endl;
  cout << "配列s4に文字列\"" << s4 << "\"が格納されています。" << endl;
  
  return 0;
}






#include <iostream>

using namespace std;

int main(void){
  char s[4] = "ABC";
  cout << s << endl;
  s[0] = '\0';
  cout << s << endl;
  return 0;
}





#include <iostream>
#include <cctype>

using namespace std;

void put_lower(const char s[]){
  for(int i = 0; i < sizeof(s); i++)
    cout << static_cast<char>(tolower(s[i]));
}

int main(void){
  char str[36];
  cout << "文字列:";
  cin >> str;
  put_lower(str);
  cout << endl;

  return 0;
}





#include <iostream>
#include <cctype>

using namespace std;

void put_lower(const char s[]){
  for(int i = 0; s[i]; i++)
    cout << static_cast<char>(tolower(s[i]));
}

int main(void){
  char str[36];
  cout << "文字列:";
  cin >> str;
  put_lower(str);
  cout << endl;

  return 0;
}






#include <iostream>

using namespace std;

int main(void){
  char str[] = "ABC";
  char* ptr = "XYZ";

  cout << "str = \"" << str << "\"" << endl;
  cout << "ptr = \"" << ptr << "\"" << endl;
  return 0;
}