I am a green hand for C++.
The following is the C++ code I wrote just now. I did not know why I was warned as "string subscript out of range". Can anybody help me? Thank you~~~
#include<iostream>
#include<string>
using std::cin;
using std::cout;
using std::string;
int main()
{
string target;
cin>>target;
string str;
int sum=0;
getline(cin,str);
string::size_type t;
for(t=1;t!=str.size();t++){
if(target[0]==str[t-1]&&target[1]==str[t])
sum++;
}
cout<<"There are "<<sum<<" pairs of the letters."<<std::endl;
return 0;
}
For those of you wondering if Vlad is playing a game of "what's your favourite line of code", the point is that getline takes care of string size for us.
use cin instead of getline. For some reason it takes the first line for getline, so both rae readed from the same line, but since that line is already read, str becomes nothing. And since for acts like do ... while, it trys to read str[0] wich doesnt exist 'cos the size of str is 0!
try this of you don't belive me:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
using std::cin;
using std::cout;
using std::string;
int main()
{
string target;
cin>>target;
string str;
int sum=0;
getline(cin, str);
string::size_type t;
cout<<str.size();
return 0;
}