STL C++中string、ifstream、stringstream的使用

来源:互联网 发布:2015淘宝快排阀严查 编辑:程序博客网 时间:2024/05/05 02:22

http://hi.baidu.com/pursuitofacm/item/8a0353ce92a28b180ad93a96




1、从标准输入接受字符串,然后进行相关处理 

 

#include<iostream>
#include<sstream>
#include<string>
using namespace std;

int main()
{
    //定义一个string对象,从标准输入接受一个字符串
    string s;
    cout<<"请输入一行字符串:"<<endl;
    getline(cin,s);
    //定义一个string流(使用s实例化)
    stringstream ss(s);
    //将string流里的东西输出
    cout<<"处理的字符串为:"<<endl;
    for(string s1;ss>>s1h;cout<<s1<<endl);
    return 0;
}

运行结果:


2.从文件读入字符串,然后进行相关处理

 

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    //定义一个文件输入流,从文件中读取

    ifstream fin("f://1.txt");
    if(!fin)
    {
        cout<<"Can not open!";
        return -1;
    }
    //定义一个string,获取文件流中的一行
    string s;
    while(getline(fin,s))
    {
        //定义一个string流(使用一个string对象填充)
        stringstream ss(s);
        int a,b;
        //将string流中的两个值分别读入a、b中
        ss>>a;ss>>b;
        cout<<"该行数据和为:"<<a+b<<endl;
    }
}

 

在F盘建一个1.txt,内容是:

1 10
2 100
3 8
4 9

 

运行结果:


参考来源:http://www.cnblogs.com/sxp227/archive/2009/02/17/1392668.html


1、从标准输入接受字符串,然后进行相关处理 

 

#include<iostream>
#include<sstream>
#include<string>
using namespace std;

int main()
{
    //定义一个string对象,从标准输入接受一个字符串
    string s;
    cout<<"请输入一行字符串:"<<endl;
    getline(cin,s);
    //定义一个string流(使用s实例化)
    stringstream ss(s);
    //将string流里的东西输出
    cout<<"处理的字符串为:"<<endl;
    for(string s1;ss>>s1h;cout<<s1<<endl);
    return 0;
}

运行结果:


2.从文件读入字符串,然后进行相关处理

 

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    //定义一个文件输入流,从文件中读取

    ifstream fin("f://1.txt");
    if(!fin)
    {
        cout<<"Can not open!";
        return -1;
    }
    //定义一个string,获取文件流中的一行
    string s;
    while(getline(fin,s))
    {
        //定义一个string流(使用一个string对象填充)
        stringstream ss(s);
        int a,b;
        //将string流中的两个值分别读入a、b中
        ss>>a;ss>>b;
        cout<<"该行数据和为:"<<a+b<<endl;
    }
}

 

在F盘建一个1.txt,内容是:

1 10
2 100
3 8
4 9

 

运行结果:


参考来源:http://www.cnblogs.com/sxp227/archive/2009/02/17/1392668.html

原创粉丝点击