C++ - 在没有 ifstream 的情况下计算单词出现次数的程序
C++ - Program to count occurrences of word without ifstream
我有一段代码,程序将从用户那里读取一个词,然后计算它在文本文件“my_data.txt”中的总出现次数。但是我不想使用 ifstream 函数。我已经有了 "the sky is blue" 这样的文本。
我想让程序从中读取。我知道我可以创建一个字符串并添加文本,但我如何计算出现次数?
到目前为止,这是我的代码:
#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后台,可以用来读取文件。为 word 开发正确的 format specifier 可能很棘手。但它不是 std::ifstream
。
此外,fscanf
不能安全地与 std::string
一起使用,而 std::ifstream
可以安全地与 std::string
一起使用。
编辑 1:字符串中的单词
由于你的问题有些含糊不清,一种解释是你想计算一串文本中的单词数。
假设您有这样的声明:
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;
}
我有一段代码,程序将从用户那里读取一个词,然后计算它在文本文件“my_data.txt”中的总出现次数。但是我不想使用 ifstream 函数。我已经有了 "the sky is blue" 这样的文本。
我想让程序从中读取。我知道我可以创建一个字符串并添加文本,但我如何计算出现次数?
到目前为止,这是我的代码:
#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后台,可以用来读取文件。为 word 开发正确的 format specifier 可能很棘手。但它不是 std::ifstream
。
此外,fscanf
不能安全地与 std::string
一起使用,而 std::ifstream
可以安全地与 std::string
一起使用。
编辑 1:字符串中的单词
由于你的问题有些含糊不清,一种解释是你想计算一串文本中的单词数。
假设您有这样的声明:
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;
}