2017-10-01 16 views
0

私は学生で、ハングマンプログラムを作ろうとしています。私は私のハングマンプログラムに使用するはずのwords.datというファイルを与えられましたが、データを格納して文字列配列に入れる方法はわかりません。私はファイルをインポートするための専用の関数を作成しようとしています。私はdatファイルにどのように言葉が入るのかわかりませんが、私の先生は100人になると言いました。これは私の大まかな推測でしたが、コンパイルしようとして多くのエラーが発生しました。どのようにdatファイルから文字列に単語を取得するのですか?あなたは、1行に1つの単語を持っているのでファイルを読み込んで文字列に格納する

COW 
SCHOOL 
KEY 
COMPUTER 

私の機能words.datこれまで

#include <string> 
#include <fsteam> 
using namespace std; 

bool initializeFile(string filename){ 
    int importWord = 0; 
    string words[100]; 

    ifstream input; 
    input.open(filename, 'r'); 
    if(input.fails){ 
     return false; 
    }   
    /* 
    Tring to make for loop that runs through 
    all the characters in input(dat file) and 
    store them into the words array. if the character isn't a letter it 
    skips it and continues to the next row 
    */ 

    for(int i=0;i< input.length();i++){ 
     if(input[i] =="\n"){ 
      importWord++; 
     } 
     if(input[i] != "\n"){ 
      words[importWord]=input[i]; 
     } 
    } 

    return true; 
} 
+0

'std :: vector'型に精通していますか?これはおそらく、未処理のC++配列よりも優れたツールです。 – templatetypedef

+0

['std :: ifstream'](http://en.cppreference.com/w/cpp/io/basic_ifstream)もその拠点も、C++でファイルや読書に関するチュートリアルを見つけるべきではないでしょう。 'length'メンバ関数、またはそれを読み込んでそれを読むのと同じように使われます。おそらく、[良い初心者の本を2冊入手しても](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)読むのですか? –

+0

そして、あなたは['std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline)関数について学ぶことに興味がありますか? –

答えて

0

、あなたは言葉で読むためにstd::getlineを使用することができます。

while ((word_count < MAXIMUM_WORDS) && (std::getline(word_file, word_from_file)) 

上記のコードは、あなたがの手間がなくなり、あなたのmain機能、にコードを置くことができるほど十分に小さいです:あなたはbreak文をカバーしている場合は、乗算の条件を使用することができます

const int MAXIMUM_WORDS = 100; 
std::string words[MAXIMUM_WORDS]; 
std::string word_from_file = 0; 
int word_count = 0; 
while (std::getline(word_file, word_from_file)) 
{ 
    if (word_count > MAXIMUM_WORDS) 
    { 
    break; 
    } 
    words[word_count] = word_from_file; 
    ++word_count; 
} 

配列を入力関数に渡します。

関連する問題