【发布时间】:2020-03-21 00:02:36
【问题描述】:
我正在编写一个 wordcount 函数,它应该能够将 stdin 中的元素读入字符串。然后对字符串求值并返回字数、行数、字符串大小和唯一字数。
我的问题是在向唯一集合中添加单词时。当我编写它以将元素添加到集合中时,它会将空格视为单词的一部分,然后完全推入我的集合中。 例子: 输入:
this is
is
a test
test
输出
a
test
is test this
line is 4
Words = 7
size is 27
Unique is 6
它总共计算 7 个单词和 6 个唯一单词。我尝试通过打印代码位来调试它,这样我就可以跟踪我出错的地方。我只能得出结论,问题出在我的 if 循环中。我该如何克服这个问题,我已经被困了一段时间了。
这是我的代码:
#include<iostream>
#include<string>
#include<set>
using std::string;
using std::set;
using std::cin;
using std::cout;
set<string> UNIQUE;
size_t sfind(const string s) //will take string a count words, add to set
{
string a;
int linecount = 0;
int state = 0; //0 represents reading whitespace/tab, 1 = reading letter
int count = 0; //word count
for(size_t i =0; i < s.length(); i++) {
a+=s[i]; //add to new string to add to set
if(state ==0) { //start at whitespace
if(state != ' ' && state != '\t') { //we didnt read whitespace
count++;
state =1;
}
}
else if(s[i]== ' ' || s[i] == '\t' || s[i] == '\n') {
state = 0;
UNIQUE.insert(a); //add to UNIQUE words
a.clear(); // clear and reset the string
}
if (s[i] == '\n') {
linecount++;
}
}
for(set<string>::iterator i = UNIQUE.begin(); i!= UNIQUE.end(); i++) {
cout << *i;
}
cout << '\n';
cout << "line is " << linecount << '\n';
return count;
}
int main()
{
char c;
string s;
while(fread(&c,1,1,stdin)) {
s+=c; //read element add to string
}
cout << "Words = " << sfind(s) << '\n';
cout << "size is " << s.length() << '\n';
cout << "Unique is "<< UNIQUE.size() << '\n';
return 0;
}
我也会用
fread(&c,1,1,stdin)
因为我以后会用它来增加字数统计功能。
【问题讨论】:
-
如果您使用
getline和std::istringstream来提取单词,这会容易得多。如果您使用了这些类,则不需要像else if(s[i]== ' ' || s[i] == '\t' || s[i] == '\n')这样的东西。 -
另外,不需要
fread。这样做的方法是使用std::getline,将整行读入一个字符串,然后将该字符串分解为单词。一次读一个字符是绝对没有必要的。
标签: c++ string debugging set word-count