[英]Beginner C++ - String Comparison
I'm a C# programmer that recently wanted to delve into something lower level so last week started learning C++ but have stumbled on something I thought would be fairly simple. 我是一名C#程序员,最近想深入研究某个较低的层次,因此上周开始学习C ++,但偶然发现了我认为相当简单的内容。
I enter the following string into my program: 我在程序中输入以下字符串:
"this is a test this test" and would expect the wordStructList to contain a list of 4 words, with occurrences of "test" and "this" set to 2. When debugging however, the string comparison (I've tried .compare and ==) always seems to increasing the value of occurrences no matter whether the comparison is true. “这是一次测试”,希望wordStructList包含4个单词的列表,其中“ test”和“ this”的出现设置为2。但是,在调试时,字符串比较(我尝试过.compare和==)似乎总是会增加出现次数的值,无论比较结果是否正确。
eg currentName = "is" word = "this" 例如currentName =“ is” word =“ this”
but occurrences is still been incremented. 但出现的次数仍在增加。
#include "stdafx.h"
using std::string;
using std::vector;
using std::find;
using std::distance;
struct Word
{
string name;
int occurrences;
};
struct find_word : std::unary_function<Word, bool>
{
string name;
find_word(string name):name(name) { }
bool operator()(Word const& w) const
{
return w.name == name;
}
};
Word GetWordStruct(string name)
{
Word word;
word.name = name;
word.occurrences = 1;
return word;
}
int main(int argc, char argv[])
{
string s;
string delimiter = " ";
vector<string> wordStringList;
getline(std::cin, s);
do
{
wordStringList.push_back(s.substr(0, s.find(delimiter)));
s.erase(0, s.find(delimiter) + delimiter.length());
if (s.find(delimiter) == -1)
{
wordStringList.push_back(s);
s = "";
}
} while (s != "");
vector<Word> wordStructList;
for (int i = 0; i < wordStringList.size(); i++)
{
Word newWord;
vector<Word>::iterator it = find_if(wordStructList.begin(), wordStructList.end(), find_word(wordStringList[i]));
if (it == wordStructList.end())
wordStructList.push_back(GetWordStruct(wordStringList[i]));
else
{
string word(wordStringList[i]);
for (vector<Word>::size_type j = 0; j != wordStructList.size(); ++j)
{
string currentName = wordStructList[j].name;
if(currentName.compare(word) == 0);
wordStructList[j].occurrences++;
}
}
}
return 0;
}
I hope the question makes sense. 我希望这个问题有意义。 Anyone shed any light on this?
有人对此有何启示? I'm also open to any tips about how to make the code more sensible/readable.
我也欢迎有关如何使代码更明智/更具可读性的任何提示。 Thanks
谢谢
The problem is the semicolon after this if
statement: 问题是在此
if
语句之后的分号:
if(currentName.compare(word) == 0);
The semicolon terminates the statement, so the next line 分号终止该语句,因此下一行
wordStructList[j].occurrences++;
is not part of the if
statement any more and will always be executed. 不再是
if
语句的一部分,将始终执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.