Lecture 02
Lecture 02
Rizoan Toufiq1
1 Assistant Professor
1 #include <iostream>
2 #include <string>
3 using namespace std;
4 int main()
5 {
6 string middleName, petName;
7 string alterEgoName;
8
9 cout << "Enter your middle name and the name of your pet.\n";
10 cin >> middleName;
11 cin >> petName;
12
13 alterEgoName = petName + " " + middleName;
14
15 cout << "The name of your alter ego is ";
16 cout << alterEgoName << "." << endl;
17
18 return 0;
19 }
New version:
static_cast<double>(9)
Old Version:
double(totalCandy)
Output
11 inStream.open("infile.dat");
12 outStream.open("outfile.dat");
13 int first, second, third;
14 inStream >> first >> second >> third;
15 outStream << "The sum of the first 3\n"
16 << "numbers in infile.dat\n"
17 << "is " << (first + second + third)
18 << endl;
19 inStream.close( );
20 outStream.close( );
21 return 0;
22 }
Sample Output:
fout.open("data.txt", ios::app);
cout.put(’a’);
if (! fin.eof( ))
cout << "Not done yet.";
else
cout << "End of the file.";
inStream.get(next);
while (! inStream.eof( ))
{
cout << next;
inStream.get(next);
}
Array (Same as C)
int i;
double d;
string s;
i = stoi("35");
// Converts the string "35" to an integer 35
d = stod("2.5");
// Converts the string "2.5" to the double 2.5
s = to_string(d*2);
// Converts the double 5.0 to a string "5.0000"
cout << i << " " << d << " " << s << endl;
1 #include <iostream>
2 #include <vector>
3 using namespace std;
4 int main( )
5 {
6 vector<int> v;
7 cout << "Enter a list of positive numbers.\n"
8 cout << "Place a negative number at the end.\n";
9 int next;
10 cin >> next;
11 while (next > 0)
12 {
13 v.push_back(next);
14 cout << next << " added. ";
15 cout << "v.size( ) = " <<v.size( ) <<endl;
16 cin >> next;
17 }
18 cout << "You entered:\n";
19 for (unsigned int i = 0; i <v.size( ); i++)
20 cout << v[i] << " ";
21 cout << endl;
22 return 0;
23 }
Sample Output
int main( )
{
using namespace std;
cout << "This program sorts numbers from lowest to highest.\n";
int array_size;
cout << "How many numbers will be sorted? ";
cin >> array_size;
IntArrayPtr a;
a = new int[array_size];
fill_array(a, array_size);
sort(a, array_size);
delete [] a;
return 0;
}
Walter Savitch,
Problem Solving with C++
- Chapter 2 to 9
Walter Savitch
Problem Solving with C++
Herbert Schildt
Teach Yourself C++