1.战前准备-字符的输入与输出

返回目录

1.字符的输入与输出

1.1.getchar与putchar,scanf与printf

#include<iostream>
using namespace std;

int main(int argc,const char *argv[]){
    char ch;
    int i = 0;
    while(ch = getchar())
    {
        cout<< i<<":"<< ch<< endl;
        i++;
    }
    return 0;
} 

所以说空格,制表符(tab)以及回车都是能够读到的。

 同理把上面换成scanf,printf效果也一样。

scanf,getchar每次取值检查缓冲区里面是否会有值,如果有值的话,便会取走。

1.2注意细节

 但是这样这行代码输出会与我们预想的不符。

#include<iostream>
using namespace std;

int main(int argc,const char *argv[]){
    char a,b;
    int count,i;
    scanf("%d",&count);
    for(i = 0;i<count;i++)
    {
        scanf("%c%c",&a,&b);
        printf("%c%c
",a,b);
    }    
    
    return 0;
} 
code

 输出的结果为什么和我们预想的不一样,在键盘的缓冲区里面会有制表符,在前面输入数字的时候有个回车还在缓冲区里面。

每次按下回车键的时候,就是程序可以向缓冲区里面取走数字了。

后面输出的时候发现缓冲区还有回车符然后取走,然后等待下一轮的输入,下一轮的输入加上回车缓冲区里面,然后程序取值。然后输出了。

所以我们的解决办法是把回车符给拿走,用getchar函数即可。

 详见下面

#include<iostream>
using namespace std;

int main(int argc,const char *argv[]){
    char a,b;
    int count,i;
    scanf("%d",&count);
    getchar();
    for(i = 0;i<count;i++)
    {
        scanf("%c%c",&a,&b);
        getchar();
        printf("%c%c
",a,b);
    }    
    
    return 0;
} 

 2字符串的输入与输出

2.1 getline(cin,s),scaf("%s",&s)

 注意上面那个是getline(cin,s),上面写的有点简单。下面都是gets()代替

#include<iostream>
using namespace std;

int main(int argc,const char *argv[]){
       char s1[10];
    string s2;
    getline(cin,s2);
    scanf("%s",s1);
    cout<<"s1:"<<s1<<endl;
    cout<<"s2:"<<s2<<endl;
    return 0;
} 

末尾自动会补上

 

返回目录

原文地址:https://www.cnblogs.com/accolade/p/12961191.html