13 February 2013

C++ Sample Programs


Example 1: CPP Program to perform global replace of a character apostrophe with double apostrophe in the input string.



1:  #include <iostream>  
2:  #include <string>  
3:  using namespace std;  
4:  int main () {  
5:  const char * userid;  
6:  userid = "madhu'sudhan'kittu'daddy";  
7:  cout<<userid<<endl;  
8:  string str;  
9:  str = userid;  
10:  size_t index = 0;  
11:  while (true) {  
12:     /* Locate the substring to replace. */  
13:     index = str.find("'", index);  
14:     if (index == string::npos) break;  
15:     /* Make the replacement. */  
16:     str.replace(index, 1, "''");  
17:     /* Advance index forward so the next iteration doesn't pick it up as well. */  
18:     index += 2;  
19:  }  
20:  cout<<str;  
21:  system("PAUSE");  
22:  return 0;  
23:  }  
O/P:

 madhu'sudhan'kittu'daddy  
 madhu''sudhan''kittu''daddy  
 press any key to continue....  
Example 2:  STL map example in CPP


1:  // Reading text file data.txt with below data into a map data structure and using iterator writing to a file called example.txt. Also used find method on map to check for 10th element .  
2:  // epluribusunum  
3:  // eagre, eager  
4:  // easement  
5:  // eau forte  
6:  // eau-de-nil  
7:  // eau-de-vie  
8:  // ebeneous  
9:  // ebriose  
10:  // ebullient  
11:  // imágenes  
12:  //  
13:  #include <iostream>  
14:  #include <fstream>  
15:  #include <string>  
16:  #include <map>  
17:  using namespace std;  
18:  int main () {  
19:   string line;  
20:   ifstream myfile1 ("data.txt");  
21:   ofstream myfile2 ("example2.txt");  
22:   std::map< string, string> data;  
23:   if (myfile1.is_open()&&myfile2.is_open())  
24:   {  
25:     int i = 0;  
26:     string line10;                       
27:    while ( myfile1.good() )  
28:    {  
29:     i++;  
30:     getline (myfile1,line);  
31:     data.insert(std::make_pair(line,line));  
32:     if(i==10)  
33:     {  
34:     line10=line; //storing images localized value  
35:     if(data.find(line)!=data.end())  
36:     cout<<" images exist in the map during insert\n";  
37:     }  
38:    }  
39:    std::map<string,string>::iterator ii = data.begin();  
40:    while(ii!=data.end())  
41:    {  
42:      myfile2 << (*ii).first;  
43:      myfile2 << "\n";    
44:      ++ii;  
45:    }  
46:     if(data.find(line)!=data.end())  
47:     cout<<" images exist in the map in find operation at the end\n";   
48:    myfile1.close();  
49:    myfile2.close();  
50:   }  
51:   else cout << "Unable to open file";  
52:  // getch();  
53:  data.clear();  
54:  system("PAUSE");  
55:   return 0;  
56:  }  

No comments:

Post a Comment