字数统计函数在将单词添加到一组唯一单词时遇到问题
Wordcount function having trouble adding words to a set of unique words
我正在编写一个字数统计函数,它应该能够将元素从 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)
因为我稍后会用更大的字数统计函数使用它。
与其编写代码试图在空格上解析字符串,不如使用 std::istringstream 进行解析。
下面是一个示例:
#include <string>
#include <iostream>
#include <sstream>
#include <set>
int main()
{
std::set<std::string> stringSet;
std::string line;
while (std::getline(std::cin, line))
{
std::istringstream oneline(line);
std::string word;
while (oneline >> word)
{
std::cout << word << "n";
stringSet.insert(word);
}
}
std::cout << "nnThere are " << stringSet.size() << " unique words";
}
现场示例
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 一组值的零开销下标运算符
- 使用一组结构,避免在一组结构中出现重复的结构
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 合并一组模板专用化
- 如何更好地检查两个 char 变量是否在一组值中?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 给定一个枢轴点,按照它们与枢轴点构成的角度递增顺序对一组点进行排序
- 如何从一组变量中查找最低值
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何通过查找迭代器结果分配给一组对的元素
- 读取一组用户输入,按升序排序,然后打印结果
- 如何从一组具有从左到右优先级的整数值创建有序整数键?
- 在 c++ 中定义一组 set 的迭代器
- 字数统计函数在将单词添加到一组唯一单词时遇到问题
- 如何在C++中生成一组唯一的哈希字符串
- 从一组集合{{中选择一组数字{1,2,3}.},{.},{.}}使得所有元素都是唯一的
- 我想得到一组唯一的n*n数组,这些数组在c++中的随机位置只包括0或1