I've tried to separate A-Z character in a given string using c++ but the separated string is not printing in the output but if I shift the "cout" statement inside the for loop it printing the characters. I don't know why its happen. please let me know if I've done any mistake.
my code
#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t; //number of test cases
while(t--)
{
string s,a,n;
int j=0,k=0;
char temp;
cin>>s; //getting string
for(int i=0; i<s.length(); i++)
{
if(s[i]>=65 && s[i]<=90) //checking for alphabets
{
a[j]=s[i];
j++;
cout<<a[j-1]<<endl;
}
else
{
n[k]=s[i];
k++;
cout<<n[k-1]<<endl;
}
}
cout<<endl<<a<<endl<<n; //this line is not printing
}
}
String a
is empty after initialization (i.e. it has length 0
). So you can't access/write any character using a[j]
, because this writes beyound the string's current bounds and yields undefined behaviour.
use...
a.push_back(s[i]);
to append a character at the end of the string.