Home > Back-end >  Why is my string not printing in a function?
Why is my string not printing in a function?

Time:10-03

Here is the code:

#include<iostream>
using namespace std;

int lengthOfLastWord(string s) {
    int i,j,n=0;
    for(i=0;s[i]!=0;i  ){
        n  ;
    }
    string s1;
    for(i=n,j=0;s[i]!=' ';i--,j  ){
        s1[j]=s[i];
    }
    cout<<s1;
};

int main(){
    string s;
    getline(cin,s);
    lengthOfLastWord(s);
}

What is the problem with the string s1? If s1 is in the for loop, s1 prints successfully.

CodePudding user response:

First and foremost, your lengthOfLastWord() function doesn't return anything so have its return type be void:

void lengthOfLastWord(string const& s) {
    //                       ^^^^^^ Preferably use const reference here to avoid making unnecessary copies at each invocation to 'lengthOfLastWord()'
    /* ... */
}

Now, the real problem is that you never initialized s1 before accessing it with s1[j] which leads to Undefined Behavior.

So, to fix your problem, just replace this line:

string s1;

with this:

string s1(n, '\0');

Demo


Alternatively, you can use std::string::push_back():

// ...
string s1;
for(i = n; s[i] != ' '; i--)
    s1.push_back(s[i]);
cout << s1;

Demo using std::string::push_back

  • Related