Reputation: 107
I'm executing a method to replace all spaces in a string with "%20". One may assume that the string has sufficient space at the end to hold the additional characters, and that one are given the "true" length of the string.
EXAMPLE:
Input: "Mr John Smith ", 13
Output: "Mr%20John%20Smith"
#include <stdio.h>
#include <string.h>
void URL(char str[], int length)
{
int spacecount = 0, index;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
{
spacecount++;
}
}
index = length + spacecount * 2;
if (length < strlen(str))
str[length] = '\0';
for (int j = length - 1; j >= 0; j--)
{
if (str[j] == ' ')
{
str[index - 1] = '0';
str[index - 2] = '2';
str[index - 3] = '%';
index = index - 3;
}
else
{
str[index - 1] = str[j];
index--;
}
}
printf("%s", str);
}
int main()
{
char str[100];
int len;
printf("Enter the string : ");
scanf("%s", str);
printf("Enter the length : ");
scanf("%d", &len);
URL(str, len);
}
On executing the above code using gcc compiler, I'm getting the segmentation fault. I understand, what is segmentation fault. I want to fix it in this program.
Upvotes: 1
Views: 117
Reputation: 736
Besides using fgets
, as proposed by @4386427, you can also use scanf
with the specifier %[^\n]
(matches anything that isn't a \n
) to read an entire line, like this:
scanf(" %[^\n]", str);
And for safety, when dealing with strings you should always limit the number of characters that can be read so that it doesn't exceed the length of the array str
, by doing:
scanf(" %99[^\n]", str);
So your main
could be:
int main()
{
char str[100];
int len;
printf("Enter the string : ");
scanf(" %99[^\n]", str);
for (int c=getchar(); c!='\n' && c!=EOF; c=getchar());
len = strlen(str);
URL(str, len);
}
Upvotes: 2
Reputation: 44274
How does
scanf("%s", str);
work?
What will str
contain if your input is: Mr John Smith
It's not doing what you think! The answer is that it will contain Mr
and thereby you don't have a string of length 13.
Use fgets
instead but remember to remove the newline.
The complete program could be:
#include <stdio.h>
#include <string.h>
void URL(char str[], int length)
{
printf("input: |%s|\n", str);
int spacecount = 0, index;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
{
spacecount++;
}
}
index = length + spacecount * 2;
str[index] = '\0';
for (int j = length - 1; j >= 0; j--)
{
if (str[j] == ' ')
{
str[index - 1] = '0';
str[index - 2] = '2';
str[index - 3] = '%';
index = index - 3;
}
else
{
str[index - 1] = str[j];
index--;
}
}
printf("output: |%s|\n", str);
}
int main()
{
char str[100];
int len;
printf("Enter the string : ");
fgets(str, 100, stdin);
len = strlen(str);
if (len > 0 && str[len-1] == '\n') str[--len] = '\0';
URL(str, len);
}
Input:
Mr John Smith
note: With 5 extra spaces after Smith
Output:
input: |Mr John Smith |
output: |Mr%20John%20Smith%20%20%20%20%20|
Upvotes: 2