#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"
.
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.
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.
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. )
By default, input returns a string. So the name and age will be stored as strings.
"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]);
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*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With