C++输入输出知识

1.strtok将字符串中的单词用' '分割出来

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<fstream>
using namespace std;
int main()
{
    /*
        fstream fin("input.txt",ios::in); fin>>value
    */
    fstream fin("output.txt",ios::out);
    char p[]="i am a student, you are a student too.";
    char *s=strtok(p," ");
    while(s!=NULL)
    {
        fin<<s;
        fin<<'\n';
        s=strtok(NULL," ");
    }
    
    return 0;
}

 

输出结果:
i
am
a
student,
you
are
a
student
too.

具有同样效果的代码:
#include<iostream>
#include<sstream>
#include<string>
using namespace std;int main()
{
    string line;
    getline(cin,line);//将回车也输入;
    stringstream ss;
    ss<<line;
    while(ss)
    {
        string word;
        ss>>word;
        cout<<word<<endl;//最后一个word为"\n"
    }
    return 0;
}

 c语言中 gets()也能将空格输入

#include"cstdio"
#include"cstring"
using namespace std;
int main()
{
    char s[100];
    gets(s);//回车做结束,且回车不会输入到字符串中,gets()合适做迷宫输入
    puts(s);
    return 0;
}

 

posted on 2015-09-04 18:08  vCoders  阅读(282)  评论(0编辑  收藏  举报

导航