質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
アルゴリズム

アルゴリズムとは、定められた目的を達成するために、プログラムの理論的な動作を定義するものです。

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

Q&A

解決済

1回答

1911閲覧

C++ テキストファイル の内容を二分探索木に読み込む

katsucurry

総合スコア3

アルゴリズム

アルゴリズムとは、定められた目的を達成するために、プログラムの理論的な動作を定義するものです。

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

0グッド

0クリップ

投稿2020/05/01 06:47

編集2020/05/01 07:55

前提・実現したいこと

大学の課題で二分探索木を使った辞書(簡易図書館みたいなもの)の作成をしています。しかし、テキストファイル を読み込み、二分探索木に書き込むことができません。
テキストファイル の中身は"本の題名","作者","出版した年"の3つです。
Insert(任意の本の追加)やdelete(任意の本の削除)などの機能を実装する予定ですが、テキストファイル を読み込めていないため作り始めることができません。そのため未完成のコードとなります。
C++初学者なため稚拙な質問、駄文、お許しください。

発生している問題・エラーメッセージ

任意のファイルの読み込み・二分探索木への書き込みができない。

該当のソースコード

C++

1#include <iostream> 2#include <fstream> 3using namespace std; 4 5class Library{ 6 public: 7 Library(); 8 string getTitle(); 9 string getAuthor(); 10 int getYear(); 11 void setTitle(string newTitle); 12 void setAuthor(string newAuthor); 13 void setYear(int newYear); 14 private: 15 string title; 16 string author; 17 int year; 18}; 19 20class BinarySearchTree { 21 public: 22 BinarySearchTree() 23 { 24 root = NULL; 25 } 26 bool isEmpty() const { return root==NULL; } 27 void insert(Library); 28 void print(); 29 private: 30 struct node 31 { 32 int key; 33 node* left; 34 node* right; 35 //treeType data; 36 Library data; 37 }; 38 node* root; 39 void printPrivate(node* Ptr); 40}; 41 42Library::Library(){ 43 44}; 45 46void Library::setTitle(string newTitle){ 47 title = newTitle; 48} 49 50void Library::setAuthor(string newAuthor){ 51 author = newAuthor; 52} 53 54void Library::setYear(int newYear){ 55 year = newYear; 56} 57 58string Library::getTitle() { 59 return title; 60} 61 62string Library::getAuthor() { 63 return author; 64} 65 66int Library::getYear(){ 67 return year; 68} 69 70void BinarySearchTree::insert(Library l){ 71 node* t = new node; 72 node* parent; 73 t->data = l; 74 t->left = NULL; 75 t->right = NULL; 76 parent = NULL; 77 // 78 if(isEmpty()) root = t; 79 else 80 { 81 // 82 node* curr; 83 curr = root; 84 // Find the Node's parent 85 while(curr) 86 { 87 parent = curr; 88 if(t->data.getTitle() > curr->data.getTitle()) curr = curr->right; 89 else curr = curr->left; 90 } 91 if(t->data.getTitle() < parent->data.getTitle()) 92 parent->left = t; 93 else 94 parent->right = t; 95 } 96 97} 98 99void BinarySearchTree::print() 100{ 101 printPrivate(root); 102} 103void BinarySearchTree::printPrivate(node* Ptr) 104{ 105 if(root != NULL) 106 { 107 if(Ptr->left) 108 { 109 printPrivate(Ptr->left); 110 } 111 cout<<" "<<Ptr->key<<" "; 112 if(Ptr->right) 113 { 114 printPrivate(Ptr->right); 115 } 116 } 117 else return; 118} 119 120//ファイル読み込み 121void readFile(BinarySearchTree *a){ 122 string fileName; 123 //ファイルの指定 124 cout<<"Enter name of input file:"; 125 cin>>fileName; 126 ifstream file; 127 file >> fileName; 128 file.open(fileName); 129 if(!file) { 130 cout<<"Error opening file. " << endl<<endl; 131 }else{ 132 string title; 133 string author; 134 int year; 135 Library l; 136 while(file >> title >> author >> year){ 137 l.setTitle(title); 138 l.setAuthor(author); 139 l.setYear(year); 140 (*a).insert(l); 141 } 142 } 143 file.close(); 144} 145 146int main() 147{ 148 //Creat a constructor 149 BinarySearchTree a; 150 151 //本の情報 152 string title; 153 string author; 154 int year; 155 156 char ch; 157 string name; 158 string fileName; 159 while(1) 160 { 161 cout<<"Select one of:"<<endl<<endl; 162 cout<< "(L)oad books from text file"<<endl; 163 cout<< "(P)rint entire library"<<endl; 164 cout<< "add a (N)ew book to the libary"<<endl; 165 cout<< "(D)elete a book from the library"<<endl; 166 cout<< "(S)earch for a book with full key data"<<endl; 167 cout<< "(M)aximum search depth"<<endl; 168 cout<< "search for a book by (T)itle"<<endl; 169 cout<< "search for a book by (A)uthor"<<endl; 170 cout<< "(C)heckout a book"<<endl; 171 cout<< "(R)eturn a book"<<endl; 172 cout<< "(Q)uit"<<endl<<endl; 173 cout<<"Enter choice: "; 174 cin>>ch; 175 switch(ch) 176 { 177 case 'L' : 178 readFile(&a); 179 break; 180 case 'P' : 181 a.print(); 182 break; 183 //任意の本を追加 184 /*case 'N' : 185 break; 186   //任意の本を削除 187 case 'D' : 188 break; 189 case 'S' : 190 break; 191 case 'M' : 192 break; 193 case 'T' : 194 break; 195 case 'A' : 196 break; 197 case 'C' : 198 break; 199 case 'R' : 200 break;*/ 201 case 'Q' : 202 return 0; 203 204 } 205 } 206}

補足情報(FW/ツールのバージョンなど)

テキストファイル の内容は以下です
HitchHiker's Guide To The Galaxy, The
Adams, Douglas
1979
Restaurant At The End of The Universe, The
Adams, Douglas
1980
Life, The Universe, and Everything
Adams, Douglas
1982
Mostly Harmless
Adams, Douglas
1992
Calculus
Stewart, James
2020
Calculus
Strang, Gilbert
2010
Calculus
Stewart, James
2012

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

episteme

2020/05/01 07:36

"本"がLibraryなの? "本"はBookで、"図書館"がLibraryじゃないの?
guest

回答1

0

ベストアンサー

テキストファイル を読み込めていないため作り始めることができません。

じゃぁ読みこむとこだけ。

C++

1//ファイル読み込み 2void readFile(BinarySearchTree* a) { 3 string fileName; 4 //ファイルの指定 5 cout << "Enter name of input file:"; 6 cin >> fileName; 7 ifstream file; 8 // file >> fileName; これ要らないよね 9 file.open(fileName); 10 if (!file) { 11 cout << "Error opening file. " << endl << endl; 12 } 13 else { 14 string title; 15 string author; 16 string year_str; 17 int year; 18 Libraly l; 19 while ( getline(file,title) && getline(file,author) && getline(file,year_str) ) { 20 year = stoi(year_str); 21 l.setTitle(title); 22 l.setAuthor(author); 23 l.setYear(year); 24 // 読めたかな? 25 cout << "title:[" << l.getTitle() << "] " 26 "author:[" << l.getAuthor() << "] " 27 "year:[" << l.getYear() << "]\n"; 28 // (*a).insert(l) とりあえずコメントアウト 29 } 30 } 31 file.close(); 32}

投稿2020/05/01 07:22

編集2020/05/01 07:39
episteme

総合スコア16614

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

katsucurry

2020/05/01 07:35

迅速な回答ありがとうございます。とても助かります。 上記のコードを実行してみたのですが、ファイル指定後のif文で"Error opening file"が出てしまいました。 これは該当のコード以外の問題でしょうか?
episteme

2020/05/01 07:37 編集

カレントディレクトリにそのファイルが無いんじゃなくて? # 僕は実行してちゃんと読みこむことを確認しました。
episteme

2020/05/01 07:40

cout << "Enter name of input file:"; cin >> fileName; ifstream file; // file >> fileName; これ要らない、てかあっちゃダメ file.open(fileName);
katsucurry

2020/05/01 07:47

プロジェクトのフォルダ内に存在しているという認識でよろしいでしょうか?フォルダ内にはファイルの存在は確認できます。 ご指摘のコード、消去しました。
episteme

2020/05/01 07:54 編集

知りませんそんなこと。あなたの開発環境知らんし。 ファイル名をfull-path で指定したらどうなります? ( d:\work\books.txt とか) あるいはcinからファイル名を読まずに直接 file.open("なんたら.txt"); したらどうなります?
katsucurry

2020/05/01 08:00 編集

本当に申し訳ないのですが、ただのスペルミスでした、、、。 Libraly -> library に書き換えたらちゃんと読み込めました! 懇切丁寧な回答、本当にありがとうございました。
episteme

2020/05/01 07:55

は? 実行時にオープン失敗したんでしょ? > Libraly -> library に書き換えたらコンパイルしました! ってどーゆーこと?
katsucurry

2020/05/01 07:57

テキストファイル の名前がlibrary.txtなのに、ファイル入力時にlibraly.txtと打ち込んでいました、、、。 誤字です。
episteme

2020/05/01 07:59

あー、「コンパイルしました!」じゃなくて「ちゃんと読みこめました」ね。
katsucurry

2020/05/01 08:01

おっしゃる通りです。大変助かりました。ありがとうございました!
episteme

2020/05/01 08:03

file >> title >> author >> year ではダメな理由わかってるかな? 教本よんでください。
katsucurry

2020/05/01 08:08

毎行の個々のデータを読み込めないからということですか、、、?
episteme

2020/05/01 08:09

file >> なんとか は一行まるっと読むことができないからです。空白があったらそこで切れます。
katsucurry

2020/05/01 08:15

なるほど、勉強になります。 ちなみになんですが、yearをstringではなくintとして保存することは可能なのでしょうか? 読み込みに成功した後このように表示されてしまいました。 terminate called after throwing an instance of 'std::invalid_argument' what(): stoi Abort trap: 6
episteme

2020/05/01 08:32

数値に変換できない文字列をyear_strに読みこんだんじゃないですか? stoi直前に year_str をprintすりゃわかる。
katsucurry

2020/05/01 08:57

year_strに該当するのはlibrary.txtの三行目で、数値なので読み込んだ箇所は合っていると思います。 そしてcout内の、l.getYear(); がlibrary.txt内の数字を表示しているので動作は正常だと思います。 しかし、上記の文(std::invalid_argument)が出てしまっている状態です、、、。
episteme

2020/05/01 09:48 編集

じゃデバッグして。 「おんぶにだっこ」は勘弁。 # 僕とこでは再現しません。全部(Calculus・Stewart, James・2012まで)読めました。
katsucurry

2020/05/01 10:59

その通りですね、自分の力で頑張ります。 とても助かりました、ありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問