#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
usingnamespace std;
int main()
{
int n, i, j=0, k;
string a, *b=new string;
cin>>a>>n;
pair<int, int> niz[n];
for (i=0; i<n; i++)
{
cin>>niz[n].first>>niz[n].second;
}
for (i=0; i<a.size(); i++)
{
if (a[i]>64)
{
b[j][0]=a[i];
for (k=1; a[i+k]<65 && i+k<a.size(); k++)
{
b[j][k]=a[i+k];
}
j++;
}
}
for (i=0; i<n; i++)
{
swap (b[niz[i].first-1], b[niz[i].second-1]);
}
for (i=0; i<j; i++)
{
cout<<b[i];
}
system ("pause");
return 0;
}
and with the debug mode "run to cursor" i lacalised the bug to line 27, the j++! How can an increment of a properly initialised variable like that cause a bug?
Type is everything. If b is a pointer to a string, what does this mean? b[j][0] = a[i];?
It isn't what you might think. As b is a pointer, b[j] treats b as an array of pointers and b[ij][0] is the first character of the j'th string. You only have one string (the one you point to) and the string length is zero, so accessing element zero is wrong.
The problem that kbw mentioned could cause other problems. It overwrites memory it shouldn't so there is a risk that j is written to by accident. Fix that problem and the j++ bug will probably be gone.
On line 21 you're still out of bounds. A newly created string has the size 0. On line 23 you discard all data and create an array of strings with the size 0.
The effects after writing out of bounds are not predictable.
It looks like he wants to sorts string by the first letter, which is the incorrect way to do it.
this code gives it away. this is a test for a ascii code greater that that is 'A' -1.
a[i]>64
He arbitrarily tries to swap integers and characters which would have devastating consequences because the size of a char and integer respectively. He doesn't know he could use Char through out the thing and make certain that problematic mashing doesn't take place.
He also accesses b the wrong way in many places. This takes some understanding of pointers.
Why I have to do is swap n words from the string a. Ther words are not seperated by any way, but each word starts with a capital letter. Thats why I try to put every subsequence in a as a seperate string in b, and then swap elements of b. So, what am I doing wrong?
I tested your program Azagaros, It's not working! First, you have to input a number n and n pairs of numbers and swap the words at those indexes! And second, It doesn't even seperate the words right! example:
input:
The bug is in the utilization of string::substr(). The parameters are starting point and size, but he is using it as iterators begin end.
Also, the first one will be empty.