C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

ファイルを単語ごとに読み取るC++プログラム?


このセクションでは、C++を使用してファイルコンテンツを単語ごとに読み取る方法を説明します。タスクは非常に簡単です。ファイルの内容を読み取るには、ファイル入力ストリームを使用する必要があります。ファイルストリームは、ファイル名を使用してファイルを開き、次にFileStreamを使用して各単語をロードし、wordという変数に保存します。次に、各単語を1つずつ印刷します。

アルゴリズム

read_word_by_word(filename)

begin
   file = open file using filename
   while file has new word, do
      print the word into the console
   done
end

ファイルコンテンツ(test_file.txt)

This is a test file. There are many words. The program will read this file word by word

#include<iostream>
#include<fstream>
using namespace std;
void read_word_by_word(string filename) {
   fstream file;
   string word;
   file.open(filename.c_str());
   while(file > word) { //take word and print
      cout << word << endl;
   }
   file.close();
}
main() {
   string name;
   cout << "Enter filename: ";
   cin >> name;
   read_word_by_word(name);
}

出力

Enter filename: test_file.txt
This
is
a
test
file.
There
are
many
words.
The
program
will
read
this
file
word
by
word

  1. C ++プログラムでの二分探索?

    二分探索は、半区間探索、対数探索、または二分探索とも呼ばれ、ソートされた配列内のターゲット値の位置を見つける検索アルゴリズムです。二分探索は、ターゲット値を配列の中央の要素と比較します。それらが等しくない場合、ターゲットが存在できない半分が削除され、残りの半分で検索が続行され、再び中央の要素がターゲット値と比較され、ターゲット値が見つかるまでこれが繰り返されます。残りの半分が空の状態で検索が終了した場合、ターゲットは配列に含まれていません。アイデアは単純ですが、バイナリ検索を正しく実装するには、特に配列の値が範囲内の整数のすべてではない場合、終了条件と中間点の計算に関する微妙な点に注意する必要

  2. C ++でテキストファイルを読み取る方法は?

    これは、テキストファイルを読み取るためのC++プログラムです。 入力 tpoint.txt is having initial content as “Tutorials point.” 出力 Tutorials point. アルゴリズム Begin    Create an object newfile against the class fstream.    Call open() method to open a file “tpoint.txt” to perform write operati