I am fairly new to C++, I am trying to replicate a code from C++ reference that turns spaces in a string to dashes. Here's the code
void sp_to_dash(const char *str){
while(*str){
if(*str==' ')
cout<<("%c", '-');
else
cout<<("%c", *str);
str++;
}
}
int main(){
sp_to_dash("hello world how are you");
int j;
cin>>j;
return 0;
}
Now this works perfectly, the output I get is
OUTPUT:
hello-world-how-are-you
However when I enclose the code in sp_to_dash function in curly braces like this
void sp_to_dash(const char *str) {
while (*str) {
if (*str==' ') {
cout << ("%c", '-');
} else {
cout << ("%c", *str);
str++;
}
}
}
The output I get is an infinite loop of dashes, I don't understand why that is, Can anyone explain to me why adding code in curly braces like this triggers an infinite loop?