1. 程式人生 > 其它 >字串輸入,輸出

字串輸入,輸出

作業  
1

#include <stdio.h> #define STLEN 81int main(void)//宣告定義陣列空間 { char words[STLEN]; //建立陣列 puts("Enter a string, please."); gets(words); // 典型用法 printf("Your string twice:\n"); printf("%s\n", words); puts(words); puts("Done."); return 0; }

2

#define a 10

void getnchar(char b[], int n);//建立儲存函式和儲存的陣列

int main(int argc, char* argv[])
{
char input[a];

printf("Please enter %d characters:\n", a - 1);//主要函式執行列印輸入輸出
getnchar(input, a);
printf("Result:\n");
puts(input);
printf("Done.\n");

return 0;
}

void getnchar(char b[], int n)
{
int i = 0;

while (i < n - 1)
{
b[i++] = getchar();//依次儲存
}
b[i] = '\0';

return;
}

  

在C語言中沒有字串型別,用字元陣列處理字串

定義

字元陣列定義:char陣列名[常量表達式][常量表達式]

一維字元陣列,用於儲存和處理一個字串。

二維字元陣列,用於同時儲存和處理多個字串


一:用scanf輸入字串,printf輸出字串

輸入輸出方法:逐個字元輸入輸出:%c整個字串輸入輸出:%s

逐個字元處理:

#include<stdio.h>

intmain(){

charch[5];

for(inti=0;i<5;i++){

scanf("%c",&ch[i]);}

for(inti=0;i<5;i++){

printf("%c",ch[i]);}

system("pause");

}

整個字串處理:

#include<stdio.h>

intmain(){charch[5];

scanf("%s",ch);

printf("%s",ch);

//無需&system("pause");

return0;

}

說明:

以字串為單位處理時,直接使用陣列名,無需&

輸入字串時,字元個數要小於陣列的長度,例如輸入5個字元,定義的字元陣列至少應該有6個元素

輸入字串時,遇到回車或空格,輸入結束,並且自動在串後面加上結束標誌'\0'

輸出字串時,遇到字串結束標誌’\0',輸出結束。

二:用字串處理函式gets,puts輸入和輸出

在<string.h>標頭檔案中

字串輸出函式puts

格式:puts(字元陣列)

功能:向顯示器輸出字串(輸出完,自動換行,即用'\n'替'\0')

說明:字元陣列必須以'\0'結束

字串輸入函式gets

格式:gets(字元陣列)

功能:從鍵盤鍵入以回車結束的字串放入字元陣列中,並自動加’\0'

說明:輸入串長度應小於字元陣列維數,字串中可以包含空格