1. 程式人生 > >c++去除空格並且放到字串陣列中

c++去除空格並且放到字串陣列中

int trim(string &s) 
 {
    if (s.empty()) 
   {
         return 0;
     }
 
     s.erase(0,s.find_first_not_of(" "));
     s.erase(s.find_last_not_of(" ") + 1);
     return 0;
 }
int main(){
	/*char c;
	showMenu();
	c=getchar();
	
	//我認為應該是不斷操作檔案吧,而不是說取出來放到記憶體裡
	//還是放到記憶體吧,用結構體
	while(c!='Q'){
		if(c=='P'){//直接讀取預設位置的檔案
			

		}
		else if(c=='A'){
			
		}
	}*/
	fstream fs("databaseShop.txt",ios::in|ios::out|ios::app);
	if(!fs){
		printf("open file wrongly!\n");
		return 1;
	}
	//getline必須只能用string,而不能用char。
	string sentence="  this   is the 2142whole   ";
	trim(sentence);// 是string&
	cout<<sentence<<endl;

	while(!sentence.empty()&&sentence.size()>0){
		int pos=sentence.find(' ');
		string sub=sentence.substr(0,pos);
		sentence=sentence.erase(0,pos);
		trim(sentence);
		cout<<"First sub:"<<sub<<endl;
		cout<<"Left sentence:"<<sentence<<endl;

	}
		
	getchar();
	getchar();
	return 0;
}