単語数の出力について

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
あや
記事: 28
登録日時: 4年前

単語数の出力について

#1

投稿記事 by あや » 4年前

入力テキスト中の文字数、単語数、行数を教える問題です.単語は、空白文字で区切られた非空白文字の列とします.
以下が入力テキストです.
NASA debuted a color picture from the Spirit rover
on Tuesday showing gray rocks peppering a Martian
lake bed awash in its natural hues of red pink
and orange Mission scientists said they were
bowled over by the spectacular quality of
the image taken with a dual camera system
called pancam that is mounted on a mast jutting
up from the rover I think my reaction has been
one of shock and awe said Jim Bell the team
member in charge of pancam Using special software
mission scientists can fly though the image zooming
in on rocks and other landscape features of interest
It is approximately the color that you would see
with your eyes if you were standing there Bell said
The resolution of course is pretty much what you
would see Pancam has 20 20 vision It is three to
four times better than any previous mission that has gone
to Mars in fact these pictures are the highest resolution
highest detailed pictures of Mars ever obtained They
are absolutely spectacular
以下が現在のコードです.
単語数:173と出力したいのですが,単語数:0と出力されてしまいます.
どこを直したらいいのか具体的に教えて下さい.よろしくお願いします.

コード:

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

// 定数定義
#define B 0 // 空白文字
#define N 1 // 通常文字

// プロトタイプ宣言
void updateWord(void);  // 単語数を更新する

// 大域変数
int word; // 単語数
int type; // 直前入力文字の種別

/********************************
メイン関数
********************************/
int main() {

	ifstream file;  // 入力ファイル  
	char ch;    // 入力文字
	int letter; // 文字数
	int line; // 行数

	// 1. 文字数、単語数、行数を0とする。
	letter = 0;
	word = 0;
	line = 0;

	// 2. 「直前入力文字の種別」を「空白文字」とする。
	type = B;

	// 3. ファイルを開く。
	file.open("test.txt");

	// 4. ファイルから1文字読み込む。
	ch = file.get();

	// 5. ファイルの未尾に到達するまで以下の処理を繰り返す。 
	while (!file.eof()) {

		// 5-1. 文字数を1増やす。
		letter++;

		// 5-2. 単語数を更新する。
		updateWord();

		// 5-3. 読み込んだ文字が改行文字ならば、行数を1増やす。
		if (ch == '\n') {
			line++;
		}

		// 5-4. ファイルから1文字読み込む。
		ch = file.get();
	}

	// 6. 入力ファイルを閉じる。
	file.close();

	// 7. 文字数、単語数、行数を出力する。
	cout << "文字数:" << letter << endl;
	cout << "単語数:" << word << endl;
	cout << "行数:" << line << endl;
}

/********************************************
単語数を更新する
********************************************/
void updateWord(void) {

	char ch=0;    // 入力文字

	// 1. 読み込んだ文字が空白文字ならば、以下の処理を行う。 
	if (isspace(ch)) {

		// 1-1. 「直前入力文字の種別」が「通常文字」ならば、単語数を1増やす。
		if (type == N) {
			word++;


			// 1-2. 「直前入力文字の種別」を「空白文字」とする。
			type = B;
		}

		// 2. そうでない場合、以下の処理を行う。 
		else {

			// 2-1. 「直前入力文字の種別」を「通常文字」とする。
			type = N;
		}
	}
}

アバター
asd
記事: 319
登録日時: 13年前

Re: 単語数の出力について

#2

投稿記事 by asd » 4年前

以下のトピックとの重複です。

viewtopic.php?f=3&t=20806
Advanced Supporting Developer
無理やりこじつけ(ぉ

返信

“C言語何でも質問掲示板” へ戻る