我正在工作的代码将从导入的文件中找到重复单词的数量。 输入流表示包含一系列行的文件。函数 将检查每行,在同一行上查找同一标记的连续出现次数,并沿着它连续出现的次数打印每个重复的标记。不重复的 令牌不会被打印。打印字符串的副本
以下是我有:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
ifstream in("file.txt");
if (! in)
{
cerr << "Could not open file.txt.";
return EXIT_FAILURE;
}
string str;
int count = 0;
int len=str.length();
while(getline(in,str)){
for(int i = 0; i < len; i++){
if(str.at(i) == str.at(i+1)){
count++;
}
else if(str.at(i) != str.at(i+1)){
i++;
}
}
cout << str << "*" << count << endl;
}
}
中的.txt包含:
hello how how are you you you you
I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge
bow wow wow yippee yippee yo yippee yippee yay yay yay
one fish two fish red fish blue fish
It's the Muppet Show, wakka wakka wakka
输出应该是:
how*2 you*4
I*3 Jack's*2 smirking*5
wow*2 yippee*2 yippee*2 yay*3
wakka*3
做这些语句做:'字符串str; int len = str.length();'?你声明一个空字符串,然后取其长度。这是必要的吗?由于空字符串的长度为零,所以使用'int len = 0;'有一个较短的方法。 – 2014-10-11 23:05:36
尝试查看[逐行读取文件](http://stackoverflow.com/q/7868936)和[如何在C++中拆分字符串?](http://stackoverflow.com/q/236129)。您应该能够从两个Stack Overflow问题开发解决方案。 – jww 2014-10-12 04:37:35