C 字元陣列 字串 輸入 輸出

2021-09-11 02:46:05 字數 1815 閱讀 9991

// char str[5] = "hello";//編譯失敗、提示字串太長

char str = ; //可以編譯通過, 可是列印直到遇到\0才結束

cout

<< str << " "

<< sizeof(str) << endl;

列印結果:  12340@ 4

str 的長度為 4

但是列印的時候會出問題,知道遇到\0才會結束

char str = "hello world";cout

<< str << " "

<< sizeof(str) << endl;cout

<< "請輸入一行字串"

<< endl;4

cin >> str;  // 123 hello worl

cout

<< "str的值為 "

<< str << endl; //str的值為 heelo (遇到第乙個[空格、製表符、換行符]即結束輸入)

cin.getline(str, 20); //最多輸入19個字元, 最後乙個字元是\0  但是str定義的長度為12,

cout

<< "str的值為"

<< str << " "

<< sizeof(str) << endl;

str的長度為12 末尾自動加乙個空白符\0

在第四行輸入  123 hello worl

然後str賦值為 123

然後繼續cin.getline  

str  = " hello worl" 注意hello前面的空格一起輸入到str中了。這個時候 str的長度已經為12了。如果在接著輸入更多字元,程式會出現異常

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!

// char str[5] = "hello";//編譯失敗、提示字串太長

char str = ; //可以編譯通過, 可是列印直到遇到\0才結束

cout

<< str << " "

<< sizeof(str) << endl;

列印結果:  12340@ 4

str 的長度為 4

但是列印的時候會出問題,知道遇到\0才會結束

char str = "hello world";cout

<< str << " "

<< sizeof(str) << endl;cout

<< "請輸入一行字串"

<< endl;4

cin >> str;  // 123 hello worl

cout

<< "str的值為 "

<< str << endl; //str的值為 heelo (遇到第乙個[空格、製表符、換行符]即結束輸入)

cin.getline(str, 20); //最多輸入19個字元, 最後乙個字元是\0  但是str定義的長度為12,

cout

<< "str的值為"

<< str << " "

<< sizeof(str) << endl;

str的長度為12 末尾自動加乙個空白符\0

在第四行輸入  123 hello worl

然後str賦值為 123

然後繼續cin.getline  

str  = " hello worl" 注意hello前面的空格一起輸入到str中了。這個時候 str的長度已經為12了。如果在接著輸入更多字元,程式會出現異常

C 字元陣列的輸入輸出 原樣輸出輸入的字串

在c 中,字元陣列的輸入輸出有兩種方式 逐個輸入輸出字元 將整個字串一次輸入或輸出 經典案例 c 輸出字串 include 預處理 using namespace std 命名空間 intmain 主函式 執行以上程式會輸出 請手動輸入長度小於10的字串 cyuyan 輸出手動輸入的字串 cyuya...

字串的輸入 輸出總結(陣列字串)

char str maxn maxn為常量char型別陣列宣告字串必須給出其大小,之後大小固定。cin和scanf 都是遇到 空格 tab 回車 結束,即一次讀取乙個單詞。include scanf s str include cin str cin.get str size 遇到回車或讀滿 siz...

c c 字元 字串輸入輸出

1.scanf 1.1 輸入字元 char ch scanf c ch 注意字元前面的取位址符 1.2 輸入字串 char str 15 scanf s str char pstr scanf s pstr 1 scanf 在輸入字串時,不讀入空格和回車,在讀入空格或回車時,輸入結束 2 輸入字串長...