0

こんにちは、クラスの絞首刑執行人プロジェクトに取り組んでいるのですが、問題が発生しました。私がやろうとしているのは、ファイルから単語のリストを取得し、1 つのランダムな単語を char 配列に入れることですが、テキストを文字列配列から char 配列に変換する方法が正確にはわかりません。現在このように見えます

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

int main(){
   ifstream infile;
   string words[25];
   string wordss;
   char cword[];
   int index=0;
   infile.open("c:\\words.txt)
   while (infile>>words){
         words[index]=words;
         index=index+1;



   }





}

もともとは、cword=words[0] のようにランダムに選択された番号を介して、単語配列の 1 つに対して cword 配列をランダムな単語にするだけでしたが、それはうまくいきませんでした。文字列配列から選択した単語をどのように変換して char 配列に使用するのだろうか?

4

1 に答える 1

0

char* cword は char cword[] の代わりに使用する必要があります。これにより、メモリを割り当てた後に単一の単語のみを格納できます。単語の長さが 10 の場合、cword = new char[10]; のように記述します。delete [] cword; によって後で割り当てられたメモリを削除することを忘れないでください。

文字列は、char[] に変換せずに、あなたがしようとしていることを行うこともできます。たとえば、次のものがあります。

string cword = "Hello"
cout<<cword[2]; // will display l
cout<<cword[0]; // will display H

通常、型キャストは次の 2 つのステートメントを使用して行われます。

static_cast<type>(variableName);   // For normal variables
reinterpret_cast<type*>(variableName);  // For pointers

サンプル コードは次のとおりです。

ifstream infile;
char words[25][20];

int index=0;
infile.open("c:\\words.txt");
while (infile>>words[index]){
   cout<<words[index]<<endl;    // display complete word
   cout<<endl<<words[index][2];  // accessing a particular letter in the word
   index=index+1;

良いコードを書くために、1 つのデータ型だけに固執することをお勧めします。まさにこのプロジェクトのために。

于 2013-11-15T08:03:40.553 に答える