Simple String manipulation problem
hey guys
i can't figure out what im doing wrong
dear God i miss PHP lol
I am using visual c++ 2010.
Code:
#include <iostream>
#include <string>
using namespace std;
int main(){
////////// practice exercise 4
string word;
string letter;
int i, numtimes, wordsize;
cout << "enter word";
cin >> word;
cout << "enter letter";
cin >> letter;
wordsize = int(word.size());
for(i = 0; i <= wordsize; ++i){
if(word[i] == letter){
numtimes++;
}
}
cout << numtimes;
system("pause");
}
I get the following error:
Code:
>c:\users\bakhtawar\documents\visual studio 2010\projects\string manipulation\string manipulation\index.cpp(55): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'char' (or there is no acceptable conversion)
1> c:\program files\microsoft visual studio 10.0\vc\include\exception(470): could be 'bool std::operator ==(const std::_Exception_ptr &,const std::_Exception_ptr &)'
1> c:\program files\microsoft visual studio 10.0\vc\include\exception(475): or 'bool std::operator ==(std::_Null_type,const std::_Exception_ptr &)'
1> c:\program files\microsoft visual studio 10.0\vc\include\exception(481): or 'bool std::operator ==(const std::_Exception_ptr &,std::_Null_type)'
1> c:\program files\microsoft visual studio 10.0\vc\include\system_error(408): or 'bool std::operator ==(const std::error_code &,const std::error_condition &)'
1> c:\program files\microsoft visual studio 10.0\vc\include\system_error(416): or 'bool std::operator ==(const std::error_condition &,const std::error_code &)'
1> while trying to match the argument list '(char, std::string)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I thought I had to do some kind of type conversion, but the method i used did not help.
any help would be greatly appreciated, thanks
x-ecutioner
Re: Simple String manipulation problem
The problem is that here if(word[i] == letter) you are comparing a char to a string.
Since you need just a letter you could change string letter; to char letter; and it should work.
Re: Simple String manipulation problem
Two things:
1. You should initialize numtimes to 0 before you use it
2. Compare word[i] to letter[0]
Re: Simple String manipulation problem
Code:
for(i = 0; i <= wordsize; ++i){
it should be
Code:
for(i = 0; i < wordsize; ++i){
Also, there is an standard library call to count the number of
occurrences of an element in a container (std::count in <algorithm>)
Re: Simple String manipulation problem
hey guys
thanks so much for all your help
much appreciated :)