Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function not returning desired string

#include <iostream>
#include <string>

using namespace std;
string wordB(string input);

int main() {
    //ask for word
    cout << "Enter a word\n";

    //get word
    string input = "";
    cin >> input;

    //return with b in between all letters
    cout << wordB(input);
    cout << endl << input;
}

string wordB(string str) {
    string rString = "";

    for (unsigned i = 0; i < str.length(); ++i) {
        rString += "B" + str.at(i);
    }
    cout << endl << rString;

    return rString;
}

Trying to display the word a users enter where between every character there is the letter "B". When I run this with the word "join" I get back "trtr".

like image 459
PfAntonio Avatar asked Sep 27 '18 14:09

PfAntonio


People also ask

What does it mean when a function doesnt return a value?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

Can functions return strings?

Learn how to return a string from a C function Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid.

Why is my function not returning a value in C?

In C there are no subroutines, only functions, but functions are not required to return a value. The correct way to indicate that a function does not return a value is to use the return type "void". ( This is a way of explicitly saying that the function returns nothing. )

Does the input function always returns a string?

By default, input returns a string. So the name and age will be stored as strings.


2 Answers

"B" + str.at(i); doesn't do what you seem to think it does; it's not string conctatenation. It says: take a char* pointer pointing to the beginning of the string literal "B", advance it by the number of characters equal to the ASCII code of character str.at(i), and treat the resulting pointer as pointing to a nul-terminated string. Unless str.at(i) happens to be '\x0' or '\x1' (unlikely), your program exhibits undefined behavior.

There are many different ways to do what you want. Here's one:

rString.push_back('B');
rString.push_back(str[i]);
like image 157
Igor Tandetnik Avatar answered Oct 20 '22 22:10

Igor Tandetnik


A particularly nice fix, available from C++14 onwards, is to write

rString += "B"s + str.at(i);

noting the s, which is a user-defined literal. That then forces the overloaded + operator on std::string to be used, rather than the built-in +, which is actually performing dubious (and potentially undefined) pointer arithmetic on the const char[2] literal "B" decayed to a const char*.

like image 34
Bathsheba Avatar answered Oct 20 '22 20:10

Bathsheba