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.