as part of my assignment a program has to take in string of characters (using character array for that), then sort it alphabetically [working]. Subsequently it shall take in character and find it in the string + give its location within the string.
// C1.3 i)
#include<iostream>
#include<cstring>
usingnamespace std;
int main()
{
char ch[100];
int i, j, t, l;
cout<<"Enter a string: ";
cin>>ch;
// C1.3 ii)
l=strlen(ch);
for(i=0;i<l;i++)
{
for(j=i+1; j<l; j++)
{
if(ch[i] > ch[j])
{
t=ch[i];
ch[i] = ch[j];
ch[j] = t;
}
}
}
cout<<"In Alphabetical Order \n";
for(i=0;i<l;i++)
{
cout<<ch[i]<<" ";
}
// C1.3 iii)
char sch;
int pos;
cout<<"Enter character to be looked for: "<<"\n";
cin>>sch;
for(i=0;i<l;i++)
{
if(ch[i]==sch)
{
cout<<"Character "<<sch<<" encountered at position: "<<pos<<"\n";
}
else
{
i++;
pos++;
}
}
return 0;
}
I've been messing around with the while loops at the end for quite a while, but pos is giving weird values. With different modifications it either overshoots to end of array length, displays zero or gives values one would expect form undefined integer.
Your problem with pos stems from the fact that you do not initialize it. It looks like you are trying to return the current position, but you never set this value to the current position.
In your case, i contains the position information so replace line 50 with: cout<<"Character "<<sch<<" encountered at position: "<<i<<"\n";
Actually I just looked closer and there are a few problems with that last loop:
In the else statement you increment i and pos (pos isn't initialized). In the case where ch[i]!=sch, then i gets incremented twice. Once in the if and once at the end of the loop.