OJ系统读入数据流的方法总结C++
来源:互联网 发布:哪个电视直播软件清晰 编辑:程序博客网 时间:2024/05/16 17:37
样例输入:
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;}
0 0
- OJ系统读入数据流的方法总结C++
- c++/c的文件读入和字符串读入总结
- 字符串读入的总结
- C语言读入文件全部内容的方法(文本文件)
- 关于字符串读入的总结
- 关于字符串读入的总结
- 字符串的读入程序总结
- 读入一行字符串的方法
- C++读入字符串的方法
- java读入文件的方法
- 数据流图的画法总结
- 面向数据流的方法设计系统的软件结构(储蓄系统)
- 面向数据流的设计方法
- 面向数据流的设计方法
- 面向数据流的设计方法
- [C/C++]OJ系统中马鞍点问题的歧义
- 3、用面向数据流的方法设计下列系统的软件结构
- 读入一行字符(包括空格)做为一个字符串的两个方法 ,C/C++
- iOS中数组遍历的方法及比较
- 寻找最大的K个数
- 百度Android语音识别SDK语义理解与解析方法
- AIX 操作系统查看文件夹及文件大小的命令
- CMake 简明教程(3)---安装及测试
- OJ系统读入数据流的方法总结C++
- TLB
- C# Nullable的类型转换问题
- nginx反向代理与nat123转发代理的区别和二者安装使用方法和优化配置
- JS HOOK
- AlertDialog的onCreateDialog与onPrepareDialog使用方法
- C语言 问号表达式记忆 表达式1?表达式2:表达式3
- 解决warning 1 line adds whitespace errors.
- jQuery Mobile的按钮