标签:style blog ar color os sp for on div
今天在stackoverflow上看到这么个问题,写完之后看了看别人的提交的答案,感觉自己的答案虽然能得出正确结果但是有点啰嗦,对于c++还是没有熟练,没有想起有istringstream,而且提问的老外写的程序bug实在是太多了,while循环啊,分号啊都不规范,不过那个return挺有意思,嘿嘿第一次见(可能是写的代码和看的代码太少了吧 ,嘿嘿 ,见笑,我也是一菜),于是我放弃了我原来的答案,修改了一下别人的答案,那个人的答案也不对,不能运行啊,所以说我自己改动了一下.
今儿记录一下,省的以后忘..
老外的提问:
1 struct client 2 { 3 string PhoneNumber; 4 string FirstName; 5 string LastName; 6 string Age; 7 }; 8 int main() 9 { 10 string data = getClientDatabase(); 11 12 vector <client> clients; 13 14 parse_string(data, clients); 15 return 0; 16 } 17 18 string getClientDatabase() 19 { 20 return 21 "(844)615-4504 Sofia Ross 57 \n" 22 "(822)516-8895 Jenna Doh 30 \n" 23 "(822)896-5453 Emily Saks 43 \n" 24 25 } 26 27 void parse_string(string data, vector <client> &clients) 28 { 29 string temp; 30 string temp1; 31 string temp2; 32 string temp3; 33 34 int i = 0; 35 int j = 0; 36 int k = 0; 37 int l = 0; 38 39 while (i < data.length()) 40 { 41 if (data.at(i) != ‘ ‘) 42 { 43 temp.push_back(data.at(i)); 44 j++; 45 } 46 else 47 { 48 clients.at(i).PhoneNumber = temp; 49 } 50 51 } 52 if (data.at(j) != ‘ ‘) 53 { 54 temp1.push_back(data.at(j)); 55 k++; 56 } 57 else 58 { 59 clients.at(i).FirstName = temp1; 60 } 61 62 if (data.at(k) != ‘ ‘) 63 { 64 temp2.push_back(data.at(k)); 65 l++; 66 } 67 else 68 { 69 clients.at(i).LastName = temp2; 70 } 71 72 if (data.at(l) != ‘ ‘) 73 { 74 temp3.push_back(data.at(l)); 75 76 } 77 else 78 { 79 clients.at(i).Age = temp3; 80 } 81 i++; 82 83 }
我的回答:
1 void parse_string(string data, vector <client> & clients) 2 { 3 struct client tempS; 4 istringstream iss(data); 5 for (size_t i=0; iss >> tempS.PhoneNumber; ++i) 6 { 7 iss >> tempS.FirstN >> tempS.LastN >> tempS.Age; 8 clients.push_back(tempS); 9 } 10 } 11 //test code 12 13 vector <client>::iterator it = clients.begin(); 14 for(; it != clients.end(); ++it ) 15 { 16 cout << it->PhoneNumber << " " 17 << it->FirstN << " " 18 << it->LastN << " " 19 << it->Age << endl; 20 }
标签:style blog ar color os sp for on div
原文地址:http://www.cnblogs.com/anonymity0day/p/4120126.html