您的位置:首页 > 编程语言 > C语言/C++

OJ系统读入数据流的方法总结C++

2014-06-17 14:56 190 查看
样例输入:

3,1,2
1,2,3,4,5

345,2324,11,2,4,0,9

对于这样的输入,应该先采用getline()函数获得一行数据,然后将这个字符串中数字取出。从字符串转换为int或者其他类型有三种方式。

方法一,纯正C++风格

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    string line;
    vector<string> str_list;
    double num[20] = {0.0};
    int length = 0;
    getline(cin,line);
    int index = 0;
    string str_temp = "";
    while(true)
    {
        index = line.find(",");
        if(-1 == index)
        {
            str_temp = line.substr(0,line.length());
            str_list.push_back(str_temp);
            break;
        }
        str_temp = line.substr(0,index);
        str_list.push_back(str_temp);
        line.erase(0,index+1);
    }
    
    vector<string>::iterator iter;
    for(iter=str_list.begin(); iter<str_list.end(); iter++)
    {
        cout<<*iter<<endl;
        istringstream double_temp(*iter);
        double_temp>>num[length++];
    }
    cout<<endl<<"double"<<endl;
    for(int i=0;i<length;i++)
        cout<<num[i]<<endl;        
    return 0;
}


方法二,半C半C++风格

#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
    string line;
    double num[20]={0.0};
    int length=0;
    getline(cin, line);
    const char *d = " ,";
    char * p;
    p = strtok(const_cast<char *>(line.c_str()),d);   //分割字符串标记
    while(p)
    {
        cout<<p<<endl;
        istringstream temp(p);     //必须包含头文件cstream,将一个string转为数据流
        temp>>num[length++];       //此方法对float和double都是合适的,对应的num[20]数组应该声明为float或double类型
        p=strtok(NULL,d);
    }
    cout<<"The num list:"<<endl;
    for(int i=0;i<length;i++)
        cout<<num[i]<<endl;
    return 0;
}


方法三,半C半C++风格

#include <cstring>
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    int i, count=0;
    string line;
    double num[20]={0};
    int length=0;
    getline(cin, line);
    const char *d = " ,";
    char * p;
    p = strtok(const_cast<char *>(line.c_str()),d);
    while(p)
    {
        cout<<p<<endl;
        num[length++] = atof(p);
        p=strtok(NULL,d);
    }
    cout<<"The num list:"<<endl;
    for(int i=0;i<length;i++)
        cout<<num[i]<<endl;
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: