Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I solved a problem. In my IDE(codeblocks) code is working as it is expected. But the CodeForces judge showing unexpected characters in the end of string.

Input:
1010100
0100101

Output:
1110001�B�_v��iv��@���_v�

Ans: 1110001


What I have tried:

This is my Code:
#include<stdio.h>
#include<string.h>
int main(void)
{
    /*declaring variables*/
    char array[100], array1[100];
    char ans[100];
    
    /* taking two separate line strings*/
    gets(array);
    gets(array1);
    
    /*length of the two strings are equal*/
int length = strlen(array);

/*comparing individual characters of two strings*/
int i=0;
while(length--){
    if(array[i]==array1[i]){
        ans[i]='0';
    }else{
    ans[i]='1';
    }
        i++;
}

/*printing desired string*/
printf(ans);
    return 0;
}


There must be something that I am missing. Please help.
Posted
Updated 27-Mar-22 20:11pm
Comments
Peter_in_2780 27-Mar-22 22:38pm    
Do you understand how C marks the end of a string?
Luc Pattyn 28-Mar-22 0:13am    
Is that a rhetorical question?\0
Peter_in_2780 28-Mar-22 0:59am    
I wish it were!

In C, a string doesn't really exist: it's an array of chars which is terminated by a null character: '\0'

If you omit the terminating null, there is no way to tell where your string was intended to end so printf just prints the content of memory - "random" data" - until it encounters a byte containing zero.
 
Share this answer
 
Comments
CPallini 28-Mar-22 2:11am    
5.
As others suggested (and Griff pointed out), in C you must zero-terminate strings, that is you must append the '\0' at the end of the string.
Try
C
#include <stdio.h>
#include <string.h>

int main(void)
{
  enum { SIZE = 100 };
  enum { IN1, IN2, OUT };

  /*declaring variables*/
  char array[3][SIZE];

  /* taking two separate line strings*/
  scanf("%s", array[IN1]);
  scanf("%s", array[IN2]);

  /* assuming the strings have the same length */
  size_t length = strlen(array[IN1]);



  for (size_t n = 0; n<length; ++n)
    array[OUT][n] = array[IN1][n] == array[IN2][n] ? '0' : '1';

  array[OUT][length] =  '\0';

  /*printing desired string*/
  printf("%s\n", array[OUT]);
  return 0;
}
 
Share this answer
 
v2
Comments
Patrice T 28-Mar-22 9:45am    
+5
CPallini 28-Mar-22 9:54am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900