string is not printing in c++ outside the a for loop - c++

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.

Since a is empty at the beginning and, as other answer says, you are writing beyond the string's current bounds, you can resize it to the size of s by doing the following:
a.resize(s.size());
and, once you are done with the work, reduce its capacity to fit the actual size:
a.shrink_to_fit();
This way you won't have memory reallocations that you might have when using std::string::push_back.

Also, you can use isupper() function in your first if condition.
But first you have to initialize s[i] into char variable at first for loop and add #include<cctype> library. Like this:
char c = s[i];
if(isupper(c)){code}

Related

why I am getting i at the end of char array?

#include<iostream>
#include<string.h>
using namespace std;
int main() {
int n;
cin>>n;
char code[n];
cin.ignore();
cin.getline(code, n);
int j=0;
for(int i=0; i<n; i++) {
if((code[i]>='A' && code[i]<='Z') || (code[i]>='a' && code[i]<='z')) {
code[j] = code[i];
j++;
}
}
code[j] = '\0';
cout<<code;
return 0;
}
input :
10
Ajith##
Expected output :
Ajith
Acutal output I'm getting :
Ajithi
why I am getting i at end of array ?
I need to print only alphabets ignoring numbers and special symbols. please help me on this
You tell the program that the input will be ten characters, including null-terminator.
Then you input only seven characters. With the null-terminator that leaves two uninitialized elements of the array, and those two elements will have indeterminate values.
Your loop still uses all ten characters, and using indeterminate values in any way leads to undefined behavior.
What is likely happening is that there's some data after the null-terminator that your program believes is characters.
The solution is std::string and only iterating over the actual length of the string, copying to another std::string.

I am writing a code for palindrome for integer, Why are my strings not comparing to be equal even when they are the same

1.Palindrome code using strings
#include<iostream>
using namespace std;
int main()
{
int t,n;
cin>>t;
while(t--)
{
cin>>n;
string num=to_string(n);
string rev;
//Reversed the string using for loop
for(int i=num.length();i>=0;i--)
{
rev+=num[i];
}
//Checking the strings if they are same
cout<<num<<" "<<rev<<endl;
if(num.compare(rev)==0)
cout<<"wins";
else
cout<<"loses";
}
return 0;
}
2.Output for n=101
101 101
loses
I tried to string method on a separate integer and compare it with other string and it worked.
I don't understand why is the compare method not returning 0.
You access num out of bounds since i = num.length() points at one character passed the last character in the string. It therefore access the terminating \0 character and that's the first character you'll copy and that's why the strings won't match.
Possible correction:
for(size_t i = num.length(); i--;) {
rev += num[i];
}
An alternative, less error prone, solution would be to create rev by using reverse iterators from num:
std::string rev(num.rbegin(), num.rend());

Finding letters in a string while ignoring everything else

For my homework, part of what I need to do is take a phrase from the user, and from there take only the letters in the phrase, ignoring numbers, spaces, and special characters. Once I find letters in the string, I need to store them into a separate variable. However, I can't get that variable to store anything outside of the if statement that looks for letters.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string line, temp;
cout << "Enter phrase to check: ";
getline(cin, line);
for(int i = 0; i < line.size(); i++)
{
if((line[i] > 64 && line[i] < 91) || (line[i] > 96 && line[i] < 123))
{
temp[i] = line[i];
}
}
cout << temp;
return 0;
}
When I run the program, temp outputs nothing. But I know the if statement is correctly finding letters, from making it print line[i] inside the if statement.
your temp variable is an empty string. temp[x] is telling the compiler to change the x-th character of that string(which doesn't make any sense, as the string doesn't have any characters!). You're lucky(or unlucky) that you aren't getting any Segmentation faults(crashes).
Just use the += operator:
temp += line[i];
Try
temp.push_back(line[i]);
It will work.
The way you're currently doing it (temp[i] = line[i];) means that each non special character in line will be placed at the same index in temp. This should usually fail since temp (a string) does not resize on indexing.
For changing the size of a string, there exists a function called string::push_back as detailed here.
Instead of indexing using temp[i], you would instead use temp.push_back(line[i]);
This function allows the string to resize itself to accommodate the new char if need be and won't throw a segmentation fault.
NB: std::string::push_back is designed to append a single char to a string. There exist multiple other ways of doing this, including Nikita Demodov's answer which shows the use of the += operator which is much more lenient and will allow appending of other strings etc. push_back is most common to the std::vector where it is used to append single items to the list.

Separating vowels from a string of string data type and storing it in a new string

#include<iostream>
using namespace std;
int main()
{
int i=0,j=0;
string a,v;
cin>>a;
while(a[i]!='\0')
{
if(a[i]=='a' || a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u' )
{
v[j]=a[i];
j++;
}
i++;
}
cout<<v;
return 0;
}
when i try to print v , nothing gets printed and i don't know why !
But, when i try to print v using while loop traversing through each character, the correct output gets printed. I want to know why ??
Use .at() instead of [], it does boundry checking and would have probably detected this error for you.
Your problem is that you have a string 'v' of undetermined space and you are appending to an arbitrary index of 'v'.
The solutions would be either replacing the code that append to v to:
v += a.at(i);
And with this you've also removed a bit of complexity in the form of that second itterator j.
OR
You can reserve space in v so that the [index] operation works. So at the beginning you can do:
cin>>a;
v.reserve(a.size())

independent things influence each other (I have no idea what is going on)

Sorry for the title, but I really have no idea what the problem is. The code looks like that (here it has no sense, but in the bigger project is has, so please, do not ask "why do you want to do....")
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
string sort (string slowo){
string litery = slowo;
for (int i=0; i<litery.length()-1; i++)
for (int j=0; j<litery.length()-1; j++)
if (litery[j]>litery[j+1])
swap(litery[j], litery[j+1]); // (3)
return litery;
}
int main()
{
fstream wordlist;
wordlist.open("wordlist_test",ios::in);
vector<string> words;
while (!wordlist.eof()){ // (4)
bool ok = true;
string word;
getline(wordlist,word);
string sorted = sort(word);
if (ok){
cout<<word<<endl; // (1)
words.push_back(word);
}
}
for (int i = 0; i<words.size(); i++){
cout<<words[i]<<endl; // (2)
}
}
There are for words in file "wordlist_tests". Program at the end should just write them to vector and write what's in vector into standard output. The problem is:
however line(1) proves that all words are ok
vector appears to be
empty in line (2)
now iteresting (probably just for me) part:
there are two ways to make it right:
I can just remove line(3) (however, if I am right, as the variable is passed to sort function through the value, it just swap two letters in independent variable; it has nothing to do with my vector), or:
I can change condition in while loop (4).
for example just like this:
int tmp = 0;
while (tmp < 5){
tmp++;
/..../
What is wrong with this code? What should I do write these words down to vector but still sort them and using this while loop? I cannot find the connection between this things (ok, I see that connection is variable word, but I do not know in what way). Any help appreciate.
What happens in swap() if one of the words is the empty sting ""?
If this happens, litery = "".
The condition in the loops will be to iterate from 0 to (unsigned) 0 - 1, which is a very large number.
You'll then execute if (litery[0] > litery[1])
litery[1] will access beyond the end of the empty string, which causes undefined behavior.
Let's fix this:
The common fix for this, is to iterate from 1 to string.length(). Here's an example:
string sort (string litery){
for (int i=1; i<litery.length(); i++)
for (int j=1; j<litery.length(); j++)
if (litery[j-1]>litery[j])
swap(litery[j-1], litery[j]);
return litery;
}