C++言語、国際符号翻訳プログラムについて

このQ&Aのポイント
  • C++言語で英文や英単語を国際符号(モールス信号)に変換するプログラムを書いています。
  • ユーザーが2つの英単語を入力し、単語がスペースで離れている場合に、モールス信号の間にスペースを挿入したいという問題に取り組んでいます。
  • 現在のプログラムでは、単語の間にスペースが1つしか挿入されていません。希望通りの結果を得るためにはどのように変更すればよいのでしょうか?
回答を見る
  • ベストアンサー

C++言語、国際符号翻訳プログラムについて

こんにちは。現在、英文、もしくは英単語、英字を国際符号(モールス信号)に訳すプログラムを書いているのですが、もしユーザーが二つの英単語を入力し、その単語がスペースで離れている場合(例として、SOS SOSもしくはsos sos)、翻訳された単語のモールス信号の間にスペースを三つ、文字の間に一つづつスペースを入れたいのですが(sos sosであれば、... --- ...   ... --- ...)コツがつかめなくて困っています(文字の間に一つスペースを入れる事に成功はしたのですが...) C++言語で経験者の方、いらっしゃいましたら是非アドバイスを御願い致します。 これが自分が今まで書き上げたコードなのですが、 #include <iostream> #include <string> #include <cctype> using namespace std; string engtomol (string, string[]); int main () { char alpha[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; string morse[81] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; string text, morsecode; char choice; char repeat='y'; cout << "Select 1 to decode Morse code to English text. Select 2 to decode English text to Morse code" << endl; cin >> choice; if (choice=='1') { cout << "NOTE. DO NOT INPUT A NON ENGLISH CHARACTER. THIS TRANSLATOR EXCLUSIVELY ONLY TRANSLATES ENGLISH ALPHABETS (CAPITALIZED AND NON CAPITALIZED) ONLY.\n"; cout << "Enter a text to translate, each word seperated by spaces if you want to translate more than one word:"; cin.get(); getline(cin,text); cout << "TEXT: " << text << endl; cout << "MORSE CODE: " << engtomol(text, morse) << endl; } else if (choice=='2') { cout << "lol"; } return 0; } string engtomol (string text, string morse[]) { int textlength = text.length(); string morsevalue; string spacesbtwletters= " "; string spacesbtwwords = " "; for (int k=0; k<textlength; k++) { if (text[k]!= ' ') //if the word(s) did not encounter a space { text[k]=toupper(text[k]); //upper case letters and lower case letters are the same hence have the same appropriate morse code. morsevalue=spacesbtwletters+=morse[text[k]-'A']+" ";//A is the first value of the array. by subtracting its finding the appropriate morse code for each letters } if (text[k]==' ') { morsevalue+spacesbtwwords; } } return morsevalue; } プログラムをコンパイルすると、(また例としてsos sosを入力したとします)。--- ... --- --- ... ---と、単語の間にスペースが一つしか表れません。どの様に変えたら、希望通りの結果が出ますか? よろしく御願い致します。

質問者が選んだベストアンサー

  • ベストアンサー
  • hitomura
  • ベストアンサー率48% (325/664)
回答No.3

ああ失礼、修正後の方のコードの変更点を演算子しか見てませんでした。 確かに修正後の方は "CQ DE SHIN" を正しく変換してくれますね。 じゃあ、" SOS" や "SOS "はどう変換されるべきとお考えで、それはその通りになりますか? また、spacesbtwletters はその名の通り「文字の間の空白」という役目を果たしていますか?

その他の回答 (2)

  • hitomura
  • ベストアンサー率48% (325/664)
回答No.2

> 何とか、希望通りにできましたが へぁ、じゃあ "CQ DE SHIN" って入力したらどうなります? 修正のヒント : engtomol() の中で変化しないはずの変数の宣言に const を追加してみましょう。

  • hitomura
  • ベストアンサー率48% (325/664)
回答No.1

んーと、自分なら std::map か文字と符号のペアクラスの配列を使って空白を特別扱いしないけど、とりあえず if (text[k]==' ') { morsevalue+spacesbtwwords; } では morsevalue は何も変わらない。 まあ、これを直しても本当にこのコードの通りなら他の問題があるんだけど、それは上を直してのお楽しみという事で。

shin_509
質問者

補足

hitomuraさん、 ご回答ありがとうございます。 何とか、希望通りにできましたが、今度はモールスを逆に英文(または英字、英単語)に変換したいのですが、自分の書いたコードだと"AAA"しか出てきません。どの様にコードを書き換えたらよいでしょうか? #include <iostream> #include <string> #include <cctype> using namespace std; string engtomol (string, string[]); string moltoeng (string, char[]); int main () { char alpha[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; string morse[81] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; string text, morsecode; char choice; char repeat='y'; while (repeat=='y') { cout << "Select 1 to decode Morse code to English text.\nSelect 2 to decode English text to Morse code" << endl; cin >> choice; if (choice=='1') { cout << "NOTE. DO NOT INPUT A NON ENGLISH CHARACTER. THIS TRANSLATOR EXCLUSIVELY TRANSLATES ENGLISH TEXTS (CAPITALIZED AND NON CAPITALIZED).\n"; cout << "Enter a text to translate, each word seperated by a space if you want to translate more than one word: "; cin.get(); getline(cin,text); cout << "TEXT: " << text << endl; cout << "MORSE CODE: " << engtomol(text, morse) << endl; } else if (choice=='2') { cout << "Enter a morsecode to translate, each letter code seperated by a space. If you want to translate more than one word, have 3 spaces between each word (for example, ... --- ... ... --- ...): "; cin.get(); getline(cin,morsecode); cout << "MORSECODE: " << morsecode << endl; cout << "TEXT: " << moltoeng (morsecode, alpha) << endl; } cout << "Would you like to continue? Press y to repeat. Press any other key to exit. "; cin >> repeat; } return 0; } string engtomol (string text, string morse[]) { int textlength = text.length(); string morsevalue; string spacesbtwletters= " "; string spacesbtwwords = " ";//2 spaces because im going to add it with spacesbtwletters so that it will = 3 for (int k=0; k<textlength; k++) { if (text[k]!= ' ') //if the word(s) did not encounter a space { text[k]=toupper(text[k]); //upper case letters and lower case letters are the same hence have the same appropriate morse code. morsevalue=spacesbtwletters+=morse[text[k]-'A']+" ";//A is the first value of the array. by subtracting its finding the appropriate morse code for each letters } if (text[k]==' ') { spacesbtwletters+=spacesbtwwords;//adds 3 spaces when there is a space between words } } return morsevalue; } string moltoeng (string morsecode, char alpha[]) { int morselength = morsecode.length(); string tran; string spacesbtwletters= " "; string spacesbtwwords = " "; for (int k=0; morsecode[k]; k++) { if (morsecode[k]!= ' ') //if the word(s) did not encounter a space { tran=spacesbtwletters+=alpha[morsecode[k]-morsecode[1]];//A is the first value of the array. by subtracting its finding the appropriate morse code for each letters } } return tran; } 現在あるコードです。逆の場合はモールス信号を入力した場合、文字同士の間には1スペースを、単語同士の間には3スペース、入力し、変換した英文は、英単語同士の間だけに1スペース開ける様に出力したいのですが(... --- ...   ... --- ...を SOS(もしくはsos) SOS等) 長文で申し訳ありませんが、どうかアドバイスをよろしく御願い致します。

関連するQ&A

  • VC++でプログラムの勉強をしています。

    プログラムは最近はじめたばかりです。While文とif文を使ってクイズを作ってみたところ、一個目のsinで入力を求めているところから無限ループになってしまいました。色々調べてcin.cler()とsin.ignore()を入れたりもしてみましたが上手くいきませんでした。どこを間違えているのでしょうか? //クイズ #include <iostream> using namespace std; int main()//cin.clear();cin.ignore();???? { int a; int b; while(1) { cout<<"ネコ型のロボットが出てくるアニメといえば?"<<endl; cout<<"A)ドラえもん B)ドラエもん C)ほりえもん D)サザエさん"<<endl; cin>>a; if(a=='A') { cout<<"ファイナルアンサー?"<<endl; cout<<"Y)Yes N)NO"<<endl; cin>>b; if(b=='Y'){break;} if(b=='N'){cout<<"ゆっくり考えてね!!"<<endl;} if(b!='Y'||'N'){cout<<"正しく入力してね!"<<endl;} } if(a=='B'||'C'||'D') { cout<<"ファイナルアンサー?"<<endl; cout<<"Y)Yes N)NO"<<endl; cin>>b; if(b=='Y'){cout<<"残念!!"<<endl;} if(b=='N'){cout<<"ゆっくり考えてね!!"<<endl;} } if(a!='A'||'B'||'C'||'D'){cout<<"正しく入力してね!"<<endl;} } cout<<"正解!!"<<endl; }

  • このプログラムを...

    現在テスト用のプログラムを書いているのですが、なかなか動いてくれません。 ソース: #include <iostream> #include <iomanip> #include <string> using namespace std; struct MovieData { string title; string director; int year; int time; }; const int ARRAY_SIZE = 2; void showItem(MovieData[ARRAY_SIZE]); int main() { MovieData part[ARRAY_SIZE]; for (int cnt = 0; cnt < ARRAY_SIZE; cnt++) { cout << "Enter the movie's name: "; cin >> part[cnt].title; cout << "Enter the director's name: "; cin >> part[cnt].director; cout << "Enter the year of release: "; cin >> part[cnt].year; cout << "Enter the movie's running time: "; cin >> part[cnt].time; } showItem(part); return 0; } void showItem(MovieData part) { cout << fixed << showpoint << setprecision(2); for (int cnt2 = 0; cnt2 < ARRAY_SIZE; cnt2++) { cout << "Name of movie: " << part[cnt2].title << endl; cout << "Director: " << part[cnt2].director << endl; cout << "Year of released: " << part[cnt2].year << endl; cout << "Running time: " << part[cnt2].time << endl; } } どこが間違っているのでしょうか?宜しくお願いします。

  • C++の無限ループを解決してください

    アルゴリズムを勉強するときに以下のソースを書きました; void weighted_quick_union_algorithm() { static const int volume = 10; enum status { terminate_, union_, find_ }; string str; status sta; vector<int> system(volume, 0); vector<int> size(volume, 1); for (int index = 0; index != volume; ++index) { system[index] = index; } do { cout<<"cin"<<endl; cin >> str; for (string::size_type index = 0; index != str.size(); ++index) str[index] = toupper(str[index]); if (str == "UNION") sta = union_; else if (str == "FIND") sta = find_; else if (str == "TERMINATE") sta = terminate_; switch (sta) { case(0): { cout << str << endl; break; } case(1): { cout << str << sta << endl; int p(0), q(0), i(0), j(0); while (cin >> p) { cin >> q; for (i = p; i != system[i]; i = system[i]); for (j = q; j != system[j]; j = system[j]); if (i == j) continue; if (size[i] < size[j]) { system[i] = j; size[j] += size[i]; } else { system[j] = i; size[i] += size[j]; } cout << p << " - " << q << endl; } cout<<"break"<<endl; break; } case(2): { cout << str << sta << endl; break; } } } while (sta); } しかし unionを入力しあと ; でwhile(cin>>p)をブレイクしたら cin break UNION1 cin break Union1 で無限ループ 結構時間かかったが間違いがわかりません ちなみに最少は while(cin>>p>>q)と書いていましたが同じ結果です。 どうかお願いします

  • Yesならこっちへ、NOならあっちへ(c++)

    取り組んでる課題で、Yとタイプしたら1のステップにいけて、Nとタイプしたら2のステップに行くというところでわからなくなってしまいました。Userにそういう選択させるのには何をどう書いたらいいのですか? --------------------------------------------------------------------- 問題:1から100までの整数をUserに選ばせ、Userに、「選んだ数字はXX以上ですか?」と質問を繰り返し、最後にUserの選んだ数字を当てるという課題です。(Userはそれに対してYes/Noでしか答えられません。) --------------------------------------------------------------------- int max=100; int min=0; int mid, x; int systemtype=y, sytemtype=n; main(){ while(1){ cout<<"1から100までで好きな数字を選んでね。"; cin>> x; if (n<=0 || n>=100){ break; } if (mid == (max + min)/2){ cout<<"選んだ数字は :" << mid << " より大きい? "<< endl; cout<<" y は YES, n は NO :" << endl; } else if(min == max){ cout<<"その数字は" << x <<endl; break; } else if(min == mid){ mid += ( max - mid)/2; cout<<"あなたの選んだ数は :" << mid <<" より大きい? "<<endl; } else if(max == mid){ mid -= (mid - min)/2; cout<<"あなたの選んだ数は:" << mid << " より大きい? "<< endl; } else cout<<"その数字は :"<< n <<endl; } return 0; }

  • C++文字列の挿入、結合のコードについて

    実行結果のような出力をするためには、 以下のコードの(ウ)(エ)(オ)の部分には何を入れたらよいのでしょうか? よろしくお願いします。 #include <iostream> #include <string> using namespace std; int main( ) { string str1="ABCDEF"; string str2="0123"; string str3; string q; do { (ウ) ; cout << str3 << endl; (エ) ; cout << str1 << endl; cout << "quit?"; cin >> q; } while ( (オ) ); cout << "終了" << endl; return 0; } <実行結果(出力結果)> ABCDEF0123 ABC123DEF quit?q ABC123DEF0123 ABC123123DEF quit?qu ABC123123DEF0123 ABC123123123DEF quit?quit 終了

  • 置換をするプログラム

    visual C++で入力された文字列に対し、#があったら%に置換するプログラムを作っています。insertを使おうと思うのですが、よくわかりません ずっと考えているのですが、ここから1週間進んでいません 教えてください #include<iostream> #include<string> #include<cstdlib> using namespace std; int main(void) { string a,s; cout <<"文字列を入力してください"<<endl; getline(cin,s); int i,j=0; while( j!= s.npos) { i=s.find_first_of("#",j); if(i==s.npos){ cout << s.substr(j) << endl; break; } if( i>0) { cout << s.substr(j, i-j); j=i; } i=s.find_first_not_of("#",j); if( i== s.npos) { a=s.substr(j); j=i; } else{ a=s.substr(j,i-j); j=i; } for(i=0; i<s.length(); i++) { if (s[i]== "#"){ s.insert(i,"%"); } cout<<a.s[i]<<endl; } } return 0; }

  • stringクラスのオブジェクト

    C++にて下記のソースをVC++にてコンパイルすると「'string'定義させていない識別子です。」などどエラーがでてしまいます。BC++では何も問題ないのですが・・・。なぜなのでしょうか? #include <iostream.h> #include <string.h> void main(){ string s; cout << "貴方の名前は?" <<endl; cin >> s; cout << s <<"さん、こんにちは"<<endl; }

  • 二分法のC++プログラム

    #include<iostream> #include<cmath> using namespace std; int main(){ double x1, x2, c, a; double x1, x2, c; cout <<"x1:"; cin >> x1; cout <<"x2:"; cin >> x2; while(x2-x1 > 0.00001){ c=(x1+x2)/2; c=(x1+x2)/2; if(cos(x1/2)*cos(c/2)>=0) x1 = c; else x2 = c; } cout << "x=" << x1 <<endl; return 0; } x1 cos(x/2)って入れると x2 -9.25596e+061 って出て cos(pi/2)って入れても同じ風に出てしまうんですがこれも同じように出るんですが故障ですか? x1に3と入れると x2が出てきて、x2は4と入れると xが3.14159と出て、3回xが出ますが、上の2つ(cos(pi/2)とcos(x/2))はx1とx2しか出ません .

  • C++:cinが上手く使えない

     そもそもcinについてあまり詳しい事は知らないのですが よろしくおねがいします。  cinを使って整数を取りこもうとする時、数字以外が 入ってしまうとおかしな動作をします。  例えば「10未満の整数値を取りこむまで続くループ」で 入力部分を作ろうとした時に、 while(1){  cout << "入力してください" << endl;  cin >> int_a;  if(int_a < 10) break; } 大体 以上の様に書くと、入力する時にアルファベットが 入ってしまうと 入力して下さい 入力して下さい …(エンドレス)… 入力して下さい となってしまいます。cinをあきらめてscanfにしてみると 今度は実行時エラーがでてしまいます。  整数を入力する事が出来て、なおかつアルファベットが 入力されても' 'で囲った値が入るようにするには どのようにすればよいでしょうか?

  • プログラムが~~~!!

    こんにちは。今、プログラム書いてるんですけど目的としては、 1、テキストファイルから文字列を読み込む。(大体数万文字) 2、それを100個ずつに区切る。 3、その百個ずつを二文字ずつ読んでいって、それがgcという文字列ならばその 百個の中での割合を示す。 4、さらに次の百個を・・・・ みたいなプログラムを書いてるんですけど一応下のような形までこぎつけましたが もう、お手上げです。 どなたか、助けてください。 #include<iostream.h> #include<stdio.h> #include<string.h> int main() { char pch[3]; int count=0; FILE *fin; fin=fopen('C:\ahowaki.dat','r'); fscanf(fin,'%s',&pch); cout<<"入力\n"; while(pch){ cin.read(pch,2); if((strcmp(pch,"gc"))==0) count++; if(count>=0 && count<=25) cout<<"Under25%\n"; if(count>=26&& count<=50) cout<<"Under50\n"; if(count>=51&& count<=75) cout<<"Under75%\n"; if(count>=76&& count<=100) cout<<"Under99%\n"; else cout<<"Over100%\n"; } return 0; fclose(fin); }

専門家に質問してみよう