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

时间:2015-01-05 22:38:28

标签: c

此代码适用于少于五个字母的单词:(但不是更高)

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

正确运行的唯一方法是增加尺寸&#39;变量?我想知道是否可以使用更大的单词来正常工作而不必增加“#”尺寸&#39;变量

2 个答案:

答案 0 :(得分:1)

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) 

答案 1 :(得分:1)

这会让你关闭

只需保存第一个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;
}