简体   繁体   中英

Why cout is not giving output for string?

My code is not giving st in output. There is no compilation error but there's no output either.

#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    cin>>s;
    string st;
    int j=0;
    transform(s.begin(),s.end(),s.begin(),::tolower);
    
    for(int i=0;i<s.size();i++) {
        if(s[i]!='a' && s[i]!='e' && s[i]!='o' && s[i]!='u' &&s[i]!='i') {
            st[j++]='.';
            st[j++]=s[i];
        }
    }
    cout<<st<<endl;
}

st[j++]=... writes beyond the end of the allocated space for the string and is undefined behaviour. It also overwrites the string's terminating nul character.

Instead, you want:

st.push_back (...);

or:

st +=...;

 transform(s.begin(),s.end(),s.begin(),::tolower);

This is actually wrong. ::tolower is deceptively difficult to use. The problem is:

  • The parameter of ::tolower is int.
  • The behaviour is undefined if the argument is not representable as unsigned char.
  • char may be a signed type, and thus its value isn't necessarily representable as unsigned char. Passing such char value would result in undefined behaviour.

The solution is to convert the char typed character into unsigned char before passing into ::tolower . Example:

std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
    return ::tolower(c);
);

Note that ::tolower processes one code unit at a time, and thus cannot work correctly with variable width character encodings such as Unicode.


The other, more obvious bug is:

 string st;

That's an empty string.

 st[j++]='.';

Here, you access the empty string outside of its bounds. The behaviour of the program is undefined.

A solution is to instead use:

st += '.';

Try using st.push_back() while dealing with things in which out of bound error can occur like string and vectors. That way you won't need to declare the size of array and can add elements easily. Do something like

string s ="wpfk"; // Taken anything, you can take by cin too.
string st;

and

for(int i=0;i<s.size();i++)
    {
        if(s[i]!='a' && s[i]!='e' && s[i]!='o' && s[i]!='u' &&s[i]!='i')
        {
            st.push_back('.');
            st.push_back(s[i]);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM