标签:+= ring 取字符串 get err str include null erro
今天真是试了各种方法,笨方法聪明方法都有了
方法1:一个字符一个字符的读取
方法2:借助strtok实现split 适用于char
方法3:借助istringstream实现split 适用于string
// 方法1:一个字符一个字符读取 #include <iostream> #include <string> #include <fstream> #include <stdlib.h> using namespace std; int main() { ifstream fin("data.txt"); if(! fin.is_open()) { cout<<"Error opening file"<<endl;exit(1); } char str; int num[10001]; int i=0;num[i] = 0; bool IsNegative = false; while(!fin.eof()){ fin.read(&str,1); if(str == ‘ ‘){ if(IsNegative) num[i] = -num[i]; printf("%d ",num[i]); i += 1;num[i] = 0; IsNegative = false; } else if(str == ‘\0‘ || str == ‘\n‘){ if(IsNegative) num[i] = -num[i]; printf("%d ",num[i]); i += 1;num[i] = 0; break; } else if(str == ‘-‘){ IsNegative = true; } else{ num[i] = num[i]*10 + (str-‘0‘); } } return 0; }
//方法2:借助strtok实现split 适用于char #include <iostream> #include <string> #include <fstream> #include <string.h> #include <stdio.h> using namespace std; int ReadNum(char *str){ int i = 0; int num = 0; if(str[0] == ‘-‘){ i += 1; } while(str[i]){ num = (str[i]-‘0‘) + num*10; i += 1; } if(str[0] == ‘-‘){ num = -num; } return num; } int main() { ifstream fin("data.txt"); if(! fin.is_open()) { cout<<"Error opening file"<<endl;exit(1); } char s[10001]; int num[101];int i = 0; fin.getline(s,10001); const char *d = " "; char *p; p = strtok(s,d); while(p) { num[i] = ReadNum(p); printf("%d ",num[i]); i+=1; p=strtok(NULL,d); } return 0; }
//方法3:借助istringstream实现split 适用于string #include <iostream> #include <string> #include <sstream> #include <fstream> using namespace std ; int ReadNum(string str){ int i = 0; int num = 0; if(str[0] == ‘-‘){ i += 1; } while(str[i]){ num = (str[i]-‘0‘) + num*10; i += 1; } if(str[0] == ‘-‘){ num = -num; } return num; } int main(){ ifstream fin("data.txt"); if(! fin.is_open()) { cout<<"Error opening file"<<endl;exit(1); } string str; getline(fin, str); string sTmp; istringstream istr(str); int num[100000];int i = 0; while(!istr.eof()){ istr >> sTmp; //get a word num[i] = ReadNum(sTmp); printf("%d ", num[i]); i += 1; } return 0; }
标签:+= ring 取字符串 get err str include null erro
原文地址:https://www.cnblogs.com/fanmu/p/9404226.html