简体   繁体   English

如何获取C中多个条目的第一个字符?

[英]How to get first chars of multiple entries in C?

This code works well for words with less than five letters: (but not for higher) 此代码适用于少于五个字母的单词:(但不适用于更高的单词)

#include <stdio.h> 

int main(void)
{
    const int size = 5; 

    char str1[size], str2[size], str3[size];

    printf("Type word1: ");
    scanf("%s", str1);

    printf("Type word2: ");
    scanf(" %s", str2);

    printf("Type word3: ");
    scanf(" %s", str3); 

    printf("First chars: '%c', '%c' e '%c'.\n", str1[0], str2[0], str3[0]); 

    return 0;
}

The only way to run correctly would increase the 'size' variable? 正确运行的唯一方法是增加“大小”变量? I wonder if it is possible to work properly with larger words without necessarily increasing the 'size' variable. 我想知道是否可以在不增加'size'变量的情况下正确处理较大的单词。

regarding this kind of line: 'scanf("%s", str1);' 

1)  the scanf format string needs to limit the number of characters input, 
    otherwise (in this case) 
    inputting a word longer than 4 char will result in a buffer overrun 

2) always check the returned value from scanf 
  to assure the input/conversion operation was successful.  

3) I would strongly suggest using fgets() and sscanf() 
   then 
   --the max number of characters is limited by a fgets() parameter, 
   --the string is null terminated, 
   --the newline is part of the string, 
      so will need to be overlayed with '\0'  

4) in the user prompts, 
   I would use: 
   printf( "\nUsing %d or less characters, enter a string:", argv[1] ); 
   where argv[1] is a command line parameter that indicates the max string length.  
   (be sure to allow for the nul terminator byte) 

This will get you close 这会让你靠近

Just save 1st char 只需保存第一个char

#include <stdio.h> 

int main(void)
{
    char str[3];
    printf("Type word1: ");
    scanf(" %c%*s", &str[0]);

    printf("Type word2: ");
    scanf(" %c%*s", &str[1]);

    printf("Type word3: ");
    scanf(" %c%*s", &str[2]);

    printf("First chars: '%c', '%c' e '%c'.\n", str[0], str[1], str[2]); 

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM