I was doing some tests with an online judge, my code is as follows:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i;
char mystring[100];
scanf("%s",mystring);
char newString[strlen(mystring)];
for(i=0;i<strlen(mystring);i++){
if(mystring[i]==toupper(mystring[i])){
newString[i] = tolower(mystring[i]);
}else{
newString[i] = toupper(mystring[i]);
}
}
printf("%s",newString);
}
The code changes the uppercase characters to lowercase and the lowercase characters to uppercase, the problem is that when compiling it throws me that it adds a strange letter at the end of the string:
Entry:
RrHRxcUsSrvSnTyolvsxHoGyzwBMzuLCUjcSeWmBAhodtEkgZjDkFjaXXAvjTvRfHuHGtopoxaeONzFFurfNlRdAvRYlnlfdIMsI
Expected output:
rRhrXCuSsRVsNtYOLVSXhOgYZWbmZUlcuJCsEwMbaHODTeKGzJdKfJAxxaVJtVrFhUhgTOPOXAEonZffURFnLrDaVryLNLFDimSi
My output:
rRhrXCuSsRVsNtYOLVSXhOgYZWbmZUlcuJCsEwMbaHODTeKGzJdKfJAxxaVJtVrFhUhgTOPOXAEonZffURFnLrDaVryLNLFDimSiÿ
As you can see it does its job perfectly except that it produces an "ÿ", where does this come from?
When compiling it from my own PC I don't see this symbol but this may be because it isn't in the alphabet on my PC or the IDE just doesn't support it.
I can fix this by simply removing the character from the array as it always happens but still this shouldn't happen.
What happens is that the character string , that is, the
string
one entered by keyboard, occupies 101 characters, but the array only supports 100. In the C language , all strings have 1 more character at the end, it is called a zero bar\0
, this means which in hexadecimal is\x00
, that's why it occupies 101 even though it's 100.For example, to write
Hola
, the string occupies 5 characters,Hola\0
.I leave the example here .
The string produces the following error:
char mystring[100]={"RrHRxcUsSrvSnTyolvsxHoGyzwBMzuLCUjcSeWmBAhodtEkgZjDkFjaXXAvjTvRfHuHGtopoxaeONzFFurfNlRdAvRYlnlfdIMsI"};
Additional data: How to solve this problem?
Increase the length to 101 characters
Put value
0
(zero) in the last position.The function
printf
is programmed not to display the\0
, and for this reason it must be entered\0
at the end of each string. Actually, what this function tries to show is the content of a pointer tochar
, since thosestrings
do not exist in C , but they do in C++ .Making your own function to display them isn't bad, but the result would be the same, it wouldn't affect performance either. You could also make a function that adds the
\0
automatically, so that the code is cleaner.All arrays have a null character at the end, which you must respect, and remember that all arrays (or arrays as you prefer to call them) start at 0, so an array of 100 can fill 99 spaces from 0 to 98 but not 99
As personal experience I suggest you write conditions with for or if, causing it to jump automatically if it is going to reach the limit