溫馨提示×

c語言如何輸入字符串

小億
68
2023-12-22 05:36:50
欄目: 編程語言

在C語言中,可以使用scanf函數(shù)或gets函數(shù)來輸入字符串。

  1. 使用scanf函數(shù):

    #include <stdio.h>
    
    int main() {
        char str[100];
        
        printf("請輸入字符串:");
        scanf("%s", str);
        
        printf("您輸入的字符串是:%s\n", str);
        
        return 0;
    }
    
  2. 使用gets函數(shù):

    #include <stdio.h>
    
    int main() {
        char str[100];
        
        printf("請輸入字符串:");
        gets(str);
        
        printf("您輸入的字符串是:%s\n", str);
        
        return 0;
    }
    

注意:使用gets函數(shù)時要注意字符串的長度,避免溢出。推薦使用fgets函數(shù)來輸入字符串,可以指定字符串的最大長度,避免溢出問題。

0