简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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