[英]how to use multiple functions in one while loop?
我試圖打開一個文本文件,並試圖計算文件中字符和單詞的數量,我創建了while“ while(!infile.eof());”來掃描整個文件,直到end為止。 但是,只有一個功能在起作用,其他功能也在打印與第一個相同的答案。
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
ifstream infile;
infile.open("tomorrow.txt");
int count1_char = 0;
int count2_word = 0;
while (!infile.eof())
{
{
char ch;
infile.get(ch); //number of characters
count1_char++;
}
{
char word[30];
infile >> word; //numner of words
count2_word++;
}
}
cout << " the number of characters :" << count1_char << endl;
cout << " the number of words :" << count2_word << endl;
infile.close();
return 0;
}
輸出:字符數:17單詞數:17按任意鍵繼續。 。 。
由於單詞由字符組成,因此您無法分別閱讀字符和單詞。 您應采用以下兩種方法之一:
第一種方法的優點是簡單。 第二種方法的優點是能夠正確解釋空格字符。
第二種方法要求您保留一個“狀態”,以區分當前字符是新單詞的一部分還是先前找到的單詞的延續。 一個簡單的標志就足夠了。 您將有一個循環,一個一個地讀取字符,將每個字符分類為空格或非空格(例如,使用std::isspace
函數),增加字符計數,並執行以下三種操作之一:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.