C++ 查找字符串中出现的单词
我似乎无法找到一个单词在10个字符串的数组中出现了多少次。代码编译时没有错误,但当我到达程序的最后一部分时,它说“Word X的出现是:”它总是显示一些大值,如45353454等。 我已经指出了下面的问题。还有为什么(s1[i]==s1[choise])不起作用 问题代码是这样的C++ 查找字符串中出现的单词,c++,arrays,string,C++,Arrays,String,我似乎无法找到一个单词在10个字符串的数组中出现了多少次。代码编译时没有错误,但当我到达程序的最后一部分时,它说“Word X的出现是:”它总是显示一些大值,如45353454等。 我已经指出了下面的问题。还有为什么(s1[i]==s1[choise])不起作用 问题代码是这样的 for(i = 0; i < CAPACITY; ++i) { if(s1[i] == choise) // Here is the problem. {
for(i = 0; i < CAPACITY; ++i)
{
if(s1[i] == choise) // Here is the problem.
{
++occurrences;
}
}
for(i=0;i
我该怎么修?
这里的所有代码仅供参考
#include <iostream>
#include <string>
using namespace std;
const int CAPACITY = 10;
int main ()
{
string s1[10];
int i;
int occurrences;
string choise;
for(i = 0; i < CAPACITY; ++i)
{
cout << "Type in a word: ";
cin >> s1[i];
}
cout << endl;
for(i = 0; i < CAPACITY; ++i)
{
cout << "String no: " << i + 1 << " is: " << s1[i] << endl;
}
cout << "\nType which word you want to find out how many times it has occurred: ";
cin >> choise;
for(i = 0; i < CAPACITY; ++i)
{
if(s1[i] == choise)
{
++occurrences;
}
}
cout << "\nWord " << choise << " occurrences are: " << occurrences;
return 0;
}
#包括
#包括
使用名称空间std;
常数int容量=10;
int main()
{
字符串s1[10];
int i;
int事件;
弦乐;
对于(i=0;is1[i];
}
cout我修复了这个问题。问题是我必须将变量“executions”初始化为0,这样它就没有随机值
编辑1:它没有运行的原因是,我将该部分的值引用设置为“无”,并且该部分包含随机值。要修复它,请在此处将其初始化为0:
string s1[10];
int i;
int occurrences; // missing initialization
string choice;
应该是这样
string s1[10];
int i;
int occurrences = 0;
string choice;
编辑2:我还创建了一个名为CAPACITY的常量,并将其设置为值10,但我忘了将其放入名为s1的字符串中,而是键入了值10,这几乎说明不需要CAPACITY常量(如果我们不在for循环中使用它)
要解决此问题,请更改以下内容:
string s1[10];
为此:
string s1[CAPACITY];
您需要初始化计数器变量:
int occurrences = 0;
否则,它会有垃圾。您需要初始化引用变量。因为局部变量在声明时持有垃圾值,这与全局变量的情况不同,它们会初始化为各自数据类型的默认值。如果您nt要回答你自己的问题(在这里完全可以),请在你的答案中包含完整的答案,任何其他研究者都可以从你的答案中获得价值。是的,我在发布我的问题后立即发现了。但是谢谢。@Johnson VDG这回答了问题,而你的答案没有。