1. 程式人生 > >c/c++字串輸入方式

c/c++字串輸入方式

提醒一句:

軟體不同,編譯器不同,CB編譯的c++採用的標頭檔案是<cstring>,而VC++ 引用的標頭檔案是<string>,以下程式採用CB編寫

1.scanf     遇空格終止

#include <iostream>
#include <cstdio>
#include <cstring>
#define N 101010
using namespace std;
int main(){
    char s[N],b[N];
    cout<<"請輸入字串:\n";
    while(~scanf("%s",s)){
        int i = 0;
        while((b[i] = s[i])!='\0') i++;
        cout<<"字串複製如下:\n";
        puts(b);
        cout<<"請輸入字串:\n";
    }
    return 0;
}

樣例:輸入中有空格,自動劃分成了兩個字串

2.gets   包括空格,遇'\n'終止

#include <iostream>
#include <cstdio>
#include <cstring>
#define N 101010
using namespace std;
int main()
{
    char s[N],b[N];
    cout<<"請輸入字串:\n";
    while(gets(s))    {
        int i = 0;
        while((b[i] = s[i])!='\0') i++;
        cout<<"字串複製如下:\n";
        puts(b);
        cout<<"請輸入字串:\n";
    }
    return 0;
}

樣例: 可讀入空格

3.getchar()   終止條件自己定,在終止之前可讀入所有的操作

#include <iostream>
#include <cstdio>
#include <cstring>
#define N 101010
using namespace std;
int main()
{
    char s[N],b[N];
    int i =  0;
    cout<<"請輸入字串:\n";
    while((s[i] = getchar())!='\n')///模仿getline
    {
        b[i] = s[i];
        i++;
    }
    cout<<"字串複製如下:\n";
        puts(b);
    return 0;
}

樣例:按回車之前,可以儲存所有的輸入

4.sscanf  暫時參考 https://www.cnblogs.com/lanjianhappy/p/6861728.html

5.cin   類似於scanf

6.getline(cin,s)   string 的特定輸入法

#include <iostream>
#include <cstdio>
#include <cstring>
#define N 101010
using namespace std;
int main()
{
    //char s[N],b[N];
    string s,b;
    cout<<"請輸入字串:\n";
    while(getline(cin,s)){
        b = s;
        cout<<"字串複製如下:\n";
       // puts(b);
        cout<<b<<endl;
        cout<<"請輸入字串:\n";
    }
    return 0;
}

樣例:可以讀入空格,以'\n'結束