question~~~help

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;
}



When you create a new string object like this:
string str;
it has a size of zero.

As such, when you then try to access it like this:
str[t-1]
you're trying to access something that doesn't exist.

You can change the size of the string to something suitable using the resize() function. There are also other ways to change the string size.
What is value of target.size()?
I think that target contains only one symbol, so target[1] is invalid addressing of a string element.
Last edited on
Moschops,

there is statement
getline(cin,str);
in the program.
Whups, so there is.

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.
eh~~~ I am still confused. Could you please clearly tell me where the problem lies? Thank you so much.
The error will depend on what data you type in when it runs. What do you type in?
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;
}
viliml, thank you, you are of great help~~~
Topic archived. No new replies allowed.