Click here to Skip to main content
15,907,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear all,

I'm a newbie in C. I'm playing with string but I faced to a weird thing that string appends the previous input into it. Please help to show me what is my issue. Here is the code:
C++
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <tvplib.h> //my  header locates string_check() function

int main()
{
char str1[11], str2[11], str3[5];
int i;

  printf("Enter first string: ");
  fgets(str1, 11, stdin);
  for (i=0; i<11; i++)
  if (str1[i]=='\n')
  {
      str1[i]='\0';
      break;
  }
  printf("String 1: %s  Length: %d\n", str1, strlen(str1));

  printf("Enter second string: ");
  fgets(str2, 11, stdin);
  for (i=0; i<11; i++)
  if (str2[i]=='\n')
  {
      str2[i]='\0';
      break;
  }
  printf("String 2: %s  Length: %d\n", str2, strlen(str2));

  printf("Result: %d\n",strcmp(str1,str2));
  printf("Enter password from keyboard: ");
  i=0;
  str3[i]='\0';
  while ((i<4) && (str3[i]!='\n'))
  {
        str3[i]=getch();
        if (str3[i]== '\n')
        {
            break;
        }
        puts("*");
        i++;
  };
  printf("String str3 value: %s\n", str3);
  if (string_check(str3) == 0)
  {
      printf("Correct Password: %s", str3);
  }
  else printf("Wrong Password: %s", str3);

  getch();
  return 0;
}
Posted
Updated 27-Jun-13 11:18am
v2

1 solution

You didn't terminate your third string with a '\0'. You probably want to write:
C++
if (str3[i]== '\n')
{
    str3[i] = '\0';
    break;
}
 
Share this answer
 
Comments
ESKADA_HUT 28-Jun-13 1:34am    
Dear nv3,

Thanks for your answer.
I tried your correction but the issue still happened. Please note that before I initialized str3 = '\0', str3 had had the value ='╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠eskada' ('eskada' is the input value of str1 or str2). After using getch() in while loop, str3 had the value 'skda╠╠╠╠╠╠╠╠╠╠╠╠eskada' ('skda' was the input while using getch() )

Please kindly help!
nv3 28-Jun-13 2:20am    
That str3 has some random value before you initialize it is quite normal. And that it shows the values of str1 and str2 can be explained by the stack layout. The strings str1 and str2 are probably allocated to the next higher addresses on your stack. So as long as str3 contains some random and non-zero characters it appears just as you described. If that is the only "issue" you have, your programs works quite normally.

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