簡體   English   中英

如何獲取C中多個條目的第一個字符?

[英]How to get first chars of multiple entries in 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;
}

正確運行的唯一方法是增加“大小”變量? 我想知道是否可以在不增加'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) 

這會讓你靠近

只需保存第一個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