【问题标题】:how to kill allien characters in my string?如何杀死我的字符串中的外来字符?
【发布时间】:2013-04-25 00:34:14
【问题描述】:

我想要做的是获取一个大输入(读取直到用户按下 enter(\n)),然后调用一个函数来放置这个输入的第一个单词(读取到'')。我的问题是,即使它看起来很简单,它也有 2 个额外的外星人字符。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> 

void findChoise(char *input, char *choise);

int main()
{
    char choise[12];
    char input[300];
    printf("give me the input: ");
    gets(input);
    printf("%s\n", input);
    printf("%s%d\n", "length of input: ", strlen(input));//for checking
    findChoise(input, choise);
    printf("%s%d\n", "length of output: ", strlen(choise));//for checking
    printf("%s\n", choise);
    return 0;
}

void findChoise(char *input, char *choise)
{
      int i=0;
      while(input[i] != ' ')
      {
          choise[i] = input[i];
          i++;
      };
}

【问题讨论】:

  • 确实希望使用fgets() 以确保安全,使用strchr() 以保持简洁。 (哦,const char * 表示 const 的正确性,在适当的情况下。)

标签: c input char output


【解决方案1】:

您已经完成的工作非常接近。您只是缺少字符串末尾的空字符(“\0”)。我已经稍微清理了您的代码并修复了一些问题。请通读并尝试了解发生了什么。

主要注意事项:

  1. 所有字符串都是字符数组,并以空字符“\0”结束
  2. 当您声明缓冲区(输入和选择)时,请尝试将它们设为 2 的幂。这与它们在内存中的存储方式有关
  3. 避免使用gets,而改用scanf

    #include <cstdio>
    
    void findChoice(char*, char*);
    
    int main() {
        char choice[16];
        char input[512];
    
        scanf("%s", input);
        findChoice(choice, input);
        printf("%s", choice);
    
        return 0;
    }
    
    void findChoice(char* input, char* choice) {
        int i = 0;
    
        while(input[i] != ' ') {
            choice[i] = input[i];
            ++i;
        }
        choice[i] = '\0';
    }
    

【讨论】:

    【解决方案2】:

    你还需要写一个空字符来结束选择字符串:

    void findChoise(char *input, char *choise)
    {
          int i=0;
          while(input[i] != ' ')
          {
              choise[i] = input[i];
              i++;
          }
          choise[i] = 0;
    }
    

    也不要使用gets:

    fgets(input, sizeof(input), stdin);
    

    并使用%zu 打印size_t

    printf("%s%zu\n", "length of input: ", strlen(input));
    

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 2023-03-08
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      相关资源
      最近更新 更多