String附加上一个输入 [英] String appends the previous input

查看:81
本文介绍了String附加上一个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,



我是C的新手。我正在玩字符串,但我遇到一个奇怪的事情,字符串将之前的输入添加到它。请帮助告诉我我的问题是什么。以下是代码:

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:

#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;
}

推荐答案

您没有使用'\0'终止第三个字符串。你可能想写:

You didn't terminate your third string with a '\0'. You probably want to write:
if (str3[i]== '\n')
{
    str3[i] = '\0';
    break;
}


这篇关于String附加上一个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆