以下は入力した文字列を全て大文字にして出力する
プログラムです。
C++
1#include<iostream> 2#include<cctype> 3using namespace std; 4 5void put_upper(const char* s){ 6 7 for (int i = 0; s[i]; i++){ 8 cout << static_cast<char>(toupper(s[i])); 9 } 10} 11 12int main(){ 13 char str[36]; 14 cout << "Whats your name? : "; cin >> str; 15 put_upper(str); 16}
C++において文字列はconst char型の配列
であるそうですが、
toupper関数というのは
C++
1void my_toupper(char *str) 2{ 3 while( *str != '\0' ) { 4 if( *str >= 'a' && *str <= 'z' ) 5 *str += 'A' - 'a'; 6 ++str; 7 } 8}
こんな感じにポインタによって、もともとの文字列の各要素を
変更してしまっています。これは文字列の各要素がconst char型であることに
矛盾するような気がするのですが、どういうことなのでしょうか。
回答お願い致します。
回答5件
あなたの回答
tips
プレビュー