I am a beginner studying C++. Currently I am studying functions, C strings, and pass by reference.
The program below is meant to take a string from input, replace any spaces with hyphens, and any exclamation marks with question marks.
If the function below, StrSpaceToHyphen() is of return type void, wouldn't the function parameter need to be pass by reference in order for userStr in main() to be modified?
The program copied below works as intended. My question is meant to further my understanding of modifying c strings as I was expecting it to behave differently.
#include <iostream>
#include <cstring>
using namespace std;
// Function replaces spaces with hyphens
void StrSpaceToHyphen(char modString[]) {
int i; // Loop index
for (i = 0; i < strlen(modString); ++i) {
if (modString[i] == ' ') {
modString[i] = '-';
}
if (modString[i] == '!') {
modString[i] = '?';
}
}
}
int main() {
const int INPUT_STR_SIZE = 50; // Input C string size
char userStr[INPUT_STR_SIZE]; // Input C string from user
// Prompt user for input
cout << "Enter string with spaces: " << endl;
cin.getline(userStr, INPUT_STR_SIZE);
// Call function to modify user defined C string
StrSpaceToHyphen(userStr);
cout << "String with hyphens: " << userStr << endl;
return 0;
}
type here
I made the function parameter pass by reference and the program wouldn't compile.
This declaration of the parameter
void StrSpaceToHyphen(char & modString[]) {
declares an array of references. You may not declare arrays of references.
As for your initial declaration
void StrSpaceToHyphen(char modString[]) {
then the compiler adjusts the parameter having the array type to pointer to the array element type like
void StrSpaceToHyphen(char *modString) {
As the address of the array is not changed within the function then there is no sense to declare the parameter as a reference to pointer like
void StrSpaceToHyphen(char * &modString) {
Having the pointer to the first element of the array and the pointer arithmetic you can change any element of the original array.
Pay attention to that the variable i and the call of strlen
are redundant.
You could define the function the following way
char * StrSpaceToHyphen( char modString[] )
{
for ( char *p = modString; *p; ++p )
{
if ( *p == ' ' )
{
*p = '-';
}
else if ( *p == '!' )
{
*p = '?';
}
}
return modString;
}