127.字符串输入输出流
1 #include<iostream> 2 //用于字符串的输入输出 3 #include<sstream> 4 #include<cstdlib> 5 #include<string> 6 //用于输出到字符串 7 #include<strstream> 8 using namespace std; 9 10 void main1() 11 { 12 //创建字符串流(sprintf) 13 stringstream mystr; 14 //输出 15 mystr.put('X').put('Y'); 16 //相当于汇总一个字符串(sprintf) 17 mystr << "1234" << 12.89 << 4; 18 cout << mystr.str() << endl; 19 20 //类似以下也可以调用 21 //mystr.put 22 //mystr.write 23 24 cin.get(); 25 } 26 27 //创建结构体,从字符串中截取字符 28 struct info 29 { 30 string str1; 31 string str2; 32 string str3; 33 int num; 34 char ch; 35 double db; 36 37 }; 38 39 void main2() 40 { 41 //从字符串中获取数据,相当于sscanf,把数据截取到结构体中 42 string str1("google microsoft apple 100 A 10.9"); 43 //创建结构体 44 info inf; 45 //建立输入流(sscanf) 46 istringstream iput(str1); 47 //从输入流获取数据到结构体中 48 iput >> inf.str1 >> inf.str2 >> inf.str3 >> inf.num >> inf.ch >> inf.db; 49 //输出结构体信息 50 cout << inf.str1 << "\n" << inf.str2 << "\n" << inf.str3 << "\n" << inf.num << "\n" << inf.ch << "\n" << inf.db; 51 52 //类似以下也可以调用 53 //iput.gcount 54 //iput.getline(); 55 56 57 cin.get(); 58 } 59 60 61 void main123213() 62 { 63 //切割数据 64 char p[100] = "google ,microsoft , apple ,100 , A , 10.9"; 65 for (char *px = p; *px != '\0'; px++) 66 { 67 if (*px == ',') 68 { 69 *px = ' '; 70 } 71 } 72 73 74 info inf; 75 //建立输入流 76 istringstream iput(p); 77 78 iput >> inf.str1 >> inf.str2 >> inf.str3 >> inf.num >> inf.ch >> inf.db;//输入 79 cout << inf.str1 << "\n" << inf.str2 << "\n" << inf.str3 << "\n" << inf.num << "\n" << inf.ch << "\n" << inf.db; 80 cin.get(); 81 } 82 83 void main123123() 84 { 85 char str[150] = { 0 };//当作缓冲区 86 //建立输出流,写到str中 87 ostringstream oput(str, sizeof(str)); 88 oput << "1233a" << 12.9 << 'A'; 89 //cout << oput.str() << endl; 90 cout << str << endl; 91 92 cin.get(); 93 } 94 95 //另外一种方法 用到头文件 strstream 96 void main1232132() 97 { 98 char str[150] = { 0 };//当作缓冲区 99 //创建输出流,输出到缓冲区中 ostrstream在strstream头文件中 100 ostrstream oput(str, sizeof(str)); 101 oput << "1233a" << 12.9 << 'A'; 102 //cout << oput.str() << endl; 103 cout << str << endl; 104 105 cin.get(); 106 }