[英]c++ count the number of occurrences of each word in string using an array?
[英]C++ - Program to count occurrences of word without ifstream
我有一個代碼,程序將從用戶那里讀取一個單詞,然后在文本文件“ my_data.txt”中計算其總出現次數。 但是我不想使用ifstream函數。 我已經有一個文字,如“天空是藍色的”。
我希望程序從中讀取。 我知道我可以創建一個字符串並添加文本,但是如何計算出現次數呢?
到目前為止,這是我的代碼:
#include<iostream.h>
#include<fstream.h>
#include<string.h>
int main()
{
ifstream fin("my_data.txt"); //opening text file
int count=0;
char ch[20],c[20];
cout<<"Enter a word to count:";
gets(c);
while(fin)
{
fin>>ch;
if(strcmp(ch,c)==0)
count++;
}
cout<<"Occurrence="<<count<<"\n";
fin.close(); //closing file
return 0;
}
如果不使用ifstream
,則有一些選擇: cin
和piping
; 或fscanf
。 我真的不明白為什么你不想使用ifstream
。
cin
和管道 您可以使用cin
流,並讓OS將數據文件路由到程序中。
您循環看起來像這樣:
std::string word;
while (cin >> word)
{
// process the word
}
使用命令行的示例調用是:
my_program.exe < my_data.txt
該調用告訴操作系統將標准輸入重定向到從文件my_data.txt
讀取的驅動程序。
fscanf
fscanf
來自C背景,可用於讀取文件。 為單詞開發正確的格式說明符可能很棘手。 但這不是std::ifstream
。
同樣, fscanf
不能與std::string
一起安全使用,而std::ifstream
可以與std::string
一起安全使用。
由於您的問題中存在一些歧義,因此一種解釋是您想從一串文本中計算單詞數。
假設您有一個這樣的聲明:
const std::string sentence = "I'm hungry, feed me now.";
您可以使用std::istringstream
並計算以下單詞:
std::string word;
std::istringstream sentence_stream(sentence);
unsigned int word_count = 0U;
while (sentence_stream >> word)
{
++word_count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.