我正在工作的代碼將從導入的文件中找到重複單詞的數量。 輸入流表示包含一系列行的文件。函數 將檢查每行,在同一行上查找同一標記的連續出現次數,並沿着它連續出現的次數打印每個重複的標記。不重複的 令牌不會被打印。打印字符串的副本
以下是我有:
#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