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++风格
方法二,半C半C++风格
方法三,半C半C++风格
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; }
相关文章推荐
- C++获取当前系统时间的方法总结
- C++调用系统中应用程序的方法的整理总结
- C++代码优化方法总结
- C++中建立对象间消息连接的一种系统方法
- C++数值--字符串间转换方法总结
- 由[ERP系统验收时测试流程方法及内容]总结现公司验收流程 2007/5/4
- C/C++系统头文件总结
- 【转贴】C++代码优化方法总结
- C++代码优化方法总结
- 屏蔽系统热键的方法总结
- 屏蔽系统热键的方法总结
- C++代码优化方法总结
- 经验总结系统文件无法打开故障解决方法
- C++代码优化方法总结
- C++代码优化方法总结
- C++代码优化方法总结
- 系统分析中写 需求说明书 的方法--个人经验总结
- C++代码优化方法总结
- 系统安全之系统密码破解方法总结
- C/C++时间函数使用方法总结