Write a C++ program to replace every space in an inputted string (less than 80 characters) with a hyphen
Write a C++ program to replace every space in an inputted string (less than 80 characters) with a hyphen (i.e. - )
Turbo C++ maharashtra board
Write a C++ program to replace every space in an inputted string (less than 80 characters) with a hyphen (i.e. - )
Turbo C++ maharashtra board
Best answer
Output of the Code ::

Answer: Read the string with cin.getline, then scan every character and replace each space with '-'.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[80];
int i, len;
clrscr();
cout << "Enter a string: ";
cin.getline(str, 80, '\n');
len = strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == ' ')
str[i] = '-';
}
cout << "Modified string: " << str;
getch();
}
How it works: cin.getline reads the whole line including spaces (plain cin >> would stop at the first space). The loop checks each character; when it finds a space it stores a hyphen in its place. Example: input I love C++ gives I-love-C++.
Log in or create a free account to answer this question.