Reputation: 33
I did a program which gets the word "SHaddOW" and dividing it to 2 words: SHOW
and add
.
That is one word of uppercase characters and the other word of lowercase chars. But I have some problem when I'm running the program.
#include <stdlib.h>
#include <string.h>
#define SIZE 10
int main()
{
int i = 0;
int countbig = 0 , countsmall = 0;
char str[] = "SHaddOW";
char smallStr[SIZE] , bigStr[SIZE];
for (i = 0; i <= strlen(str) ; i++)
{
if (str[i]>= 'A' && str[i]<='Z')
{
bigStr[countbig] = str[i];
countbig++;
}
else if (str[i] >= 'a' && str[i] <= 'z')
{
smallStr[countsmall] = str[i];
countsmall++;
}
}
puts(smallStr);
puts(bigStr);
system("PAUSE");
return 0;
}
When I'm running the program its showing that:
Upvotes: 0
Views: 71
Reputation: 1901
This happen because of not doing null termination so , Do initialization for
char smallStr[SIZE] = {0} , bigStr[SIZE] = {0};
or
Do the null termination after loop completed at end of loop do
smallStr[ countsmall ] = '\0';
bigStr[ countbig ] = '\0';
You will get correct result.
Upvotes: 1
Reputation: 786
Try this code
#include <stdlib.h>
#include <string.h>
#define SIZE 10
int main()
{
int i = 0;
int countbig = 0 , countsmall = 0;
char str[] = "SHaddOW";
char smallStr[SIZE] , bigStr[SIZE];
for (i = 0; i < strlen(str) ; i++)
{
if (str[i]>= 'A' && str[i]<='Z')
{
bigStr[countbig] = str[i];
countbig++;
}
else if (str[i] >= 'a' && str[i] <= 'z')
{
smallStr[countsmall] = str[i];
countsmall++;
}
}
bigStr[countbig]='\0';
smallStr[countsmall] = '\0';
puts(smallStr);
puts(bigStr);
system("PAUSE");
return 0;
}
You should add \0
to end the string and only travel till i
is less than length of the string.
Upvotes: 1
Reputation: 441
#include <stdlib.h>
#include <string.h>
#define SIZE 10
int main()
{
int i = 0;
int countbig = 0 , countsmall = 0;
char str[] = "SHaddOW";
char smallStr[SIZE] , bigStr[SIZE];
for (i = 0; i <= strlen(str) ; i++)
{
if (str[i]>= 'A' && str[i]<='Z')
{
bigStr[countbig] = str[i];
countbig++;
}
if (str[i] >= 'a' && str[i] <= 'z')
{
smallStr[countsmall] = str[i];
countsmall++;
}
}
bigStr[countbig] ='\0'; //you need to add null character at the end
smallStr[countsmall] = '\0';//you need to add null character at the end
puts(smallStr);
puts(bigStr);
system("PAUSE");
return 0;
}
Upvotes: 0
Reputation: 70333
puts( smallStr );
This keeps on writing whatever smallStr
is pointing to, until it hits a null byte ('\0'
).
You never write a null byte into either smallStr
or bigStr
, so you see the garbled output you are observing. (Be happy the program did not crash, as it is accessing memory it should not.)
At the end of the loop, terminate the strings:
smallStr[ countsmall ] = '\0';
bigStr[ countbig ] = '\0';
That should help.
Upvotes: 3