CPP_Programs_FileHandling_Pointers_Strings
CPP_Programs_FileHandling_Pointers_Strings
BY
MUHAMMAD RAYAN
BSCS-M1(1ST SEMESTER)
LAHORE
1. Write to a file
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fout("example.txt");
fout << "Hello World!";
fout.close();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("example.txt");
string data;
while (getline(fin, data)) {
cout << data << endl;
}
fin.close();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("example.txt");
string word;
int wordCount = 0, sentenceCount = 0;
char ch;
while (fin.get(ch)) {
if (ch == ' ' || ch == '\n') wordCount++;
if (ch == '.' || ch == '?' || ch == '!') sentenceCount++;
}
fin.close();
cout << "Words: " << wordCount + 1 << endl;
cout << "Sentences: " << sentenceCount << endl;
return 0;
}
📍 Pointers
1. Pointer to int
#include <iostream>
using namespace std;
int main() {
int a = 10;
int *p = &a;
cout << *p << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int arr[3] = {1, 2, 3};
int *p = arr;
for (int i = 0; i < 3; i++) {
cout << *(p + i) << " ";
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
swap(&a, &b);
cout << a << " " << b << endl;
return 0;
}
🧵 Strings
1. Concatenation
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello", s2 = "World";
string s3 = s1 + " " + s2;
cout << s3 << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Programming";
cout << s.length() << endl;
cout << s.substr(0, 6) << endl;
return 0;
}
3. Compare Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "Apple", b = "Banana";
if (a == b)
cout << "Equal" << endl;
else
cout << "Not Equal" << endl;
return 0;
}