0% found this document useful (0 votes)
21 views5 pages

C++ Data Conversion and File Handling

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

C++ Data Conversion and File Handling

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Conversion

#include <iostream>
using namespace std;

// Class representing distance in meters


class Distance {
private:
int meters;

public:
// Default ructor
Distance(int m = 0) : meters(m) {}

// Basic to Class Type conversion (float feet to meters)


Distance(float feet) {
meters = static_cast<int>(feet * 0.3048); // Convert feet to me
ters
}

// Class to Basic Type conversion (convert meters to int)


operator int() {
return meters;
}

// Class to Basic Type conversion (convert meters to float)


operator float() {
return static_cast<float>(meters);
}

void display() {
cout << meters << " meters" << endl;
}

int getMeters() {
return meters;
}
};

// Class representing distance in kilometers


class KiloDistance {
private:
float kilometers;

public:
// Default ructor
KiloDistance(float km = 0.0) : kilometers(km) {}
// One Class to Another Class Type conversion (Distance to KiloDist
ance)
KiloDistance( Distance& dist) {
// Convert meters to kilometers
kilometers = [Link]() / 1000.0f;
}

void display() {
cout << kilometers << " kilometers" << endl;
}

float getKilometers() {
return kilometers;
}
};

int main() {
// Basic to Class Type conversion
// Convert float (feet) to Distance (meters)
Distance d1 = 10.0f; // 10 feet converted to meters
cout << "Basic to Class Type Conversion:" << endl;
[Link](); // Displays meters

// Class to Basic Type conversion


// Convert Distance to int (meters)
int meters = d1; // Implicit conversion to int
cout << "\nClass to Basic Type Conversion:" << endl;
cout << "Distance in meters (int): " << meters << endl;

// Another Class to Basic Type conversion


// Convert Distance to float
float floatMeters = d1;
cout << "Distance in meters (float): " << floatMeters << endl;

// One Class to Another Class Type conversion


// Convert Distance to KiloDistance
cout << "\nOne Class to Another Class Type Conversion:" << endl;
KiloDistance kd = d1; // Convert meters to kilometers
[Link](); // Displays kilometers

// Data Conversion Example


Distance d2(5000); // 5000 meters
KiloDistance kd2 = d2; // Convert 5000 meters to kilometers

cout << "\nData Conversion Example:" << endl;


cout << "Original Distance: ";
[Link]();
cout << "Converted to Kilometers: ";
[Link]();
return 0;
}

File Operations
#include <iostream>
#include <fstream>
using namespace std;

int main() {
string filename = "[Link]";

// 6.4 Opening and Closing a File


fstream file; // Create a file stream (for both reading and writing)

// Open file for writing (creating if not exists)


[Link](filename, ios::out); // Open file in output mode
if (file.is_open()) {
file << "Hello, File Processing in C++!" << endl; // Write to f
ile
file << "This is a second line." << endl; // Write another line
file << "Reading characters is fun!" << endl; // Write another
line
cout << "File created and written successfully!" << endl;
[Link](); // Close the file after writing
} else {
cout << "Failed to open the file for writing!" << endl;
}

// 6.4 Reading the file Line by Line


[Link](filename, ios::in); // Open file in input mode for readin
g
if (file.is_open()) {
string line;
cout << "\nReading from the file (Line by Line):" << endl;
while (getline(file, line)) { // Read each line
cout << line << endl; // Display file contents line by line
}
[Link](); // Close the file after reading
} else {
cout << "Failed to open the file for reading!" << endl;
}

// 6.4 Reading the file Character by Character


[Link](filename, ios::in); // Open file in input mode for readin
g
if (file.is_open()) {
char ch;
cout << "\nReading from the file (Character by Character):" <<
endl;
while ([Link](ch)) { // Read each character
cout << ch; // Display the character
}
cout << endl; // Move to the next line after reading all charac
ters
[Link](); // Close the file after reading
} else {
cout << "Failed to open the file for reading!" << endl;
}

// 6.5 Deleting a File


// Open the file in output mode to delete its contents (overwrite)
[Link](filename, ios::out | ios::trunc); // Open in truncate mod
e (clear contents)
if (file.is_open()) {
cout << "\nFile contents deleted!" << endl;
[Link](); // File is truncated (emptied)
} else {
cout << "Failed to open the file for deletion!" << endl;
}

// 6.6 File Modes (Append Mode)


[Link]("[Link]", ios::out | ios::app); // Open file in app
end mode
if (file.is_open()) {
file << "Appending new data!" << endl; // Append data to the fi
le
cout << "Data appended to file successfully!" << endl;
[Link](); // Close the file after appending
} else {
cout << "Failed to open the file in append mode!" << endl;
}

return 0;
}

String Functions
#include <iostream>
#include <string>
using namespace std;

int main() {
string name = "Teja";
string lastname = "Patil";
string fullname = [Link](lastname); // String concatenation
cout << "Full name is: " << fullname << endl;

string nickname = "Tejo";


int n = [Link](nickname); // String comparison
if (n == 0) {
cout << name << " is equal to " << nickname << endl;
} else if (n < 0) {
cout << name << " is smaller than " << nickname << endl;
} else {
cout << name << " is bigger than " << nickname << endl;
}

// Find the position of a character in the string


int pos = [Link]("z"); // Finding position of "Te"
if(pos>-1){
cout << "'Te' found at position: " << pos << endl;
} else {
cout << "'Te' not found in the string!" << endl;
}

// String reversing
string rev_str([Link](), [Link]()); // Reverse the string
cout << "Reversed string: " << rev_str << endl;

return 0;
}

Common questions

Powered by AI

When a new entry is appended to a file opened in ios::app mode, the new data is added to the end of the file without altering the existing contents. This mode is significant because it ensures the integrity of all pre-existing data in the file while allowing modifications, making it ideal for operations like logging where the history of changes needs to be preserved.

When using the find() function in the code to locate a substring within a string, potential errors include the substring not being present, which is handled by checking if the find() function returns -1. If -1 is returned, it indicates the substring wasn't found, leading the code to output a specific message indicating the failure of finding the substring. This approach robustly handles the potential absence of the searched substring and avoids runtime errors related to out-of-bounds access.

Class-type conversion operators in C++ allow implicit conversions between class objects and basic data types, improving code readability and simplifying operations like arithmetic on custom types. However, disadvantages include the potential for implicit conversions leading to unexpected results if developers are not careful, and the possibility of making code maintenance harder due to reduced explicitness in how types are transformed.

The KiloDistance class converts a Distance object by using a constructor that takes a reference to a Distance object. It accesses the meters value of the Distance object via the getMeters() method, dividing this value by 1000.0 to convert meters into kilometers. Precision considerations include the fact that converting an integer meters value to a float kilometers value involves a potential precision loss, especially when performing division operations.

The reversal of a string in the provided code is implemented by leveraging the string constructor with the parameters set to the original string's reverse iterators, rbegin() and rend(). This creates a new reversed string efficiently. While this method is concise and leverages C++'s powerful standard library, it assumes the availability of sufficient memory to hold the reversed data, which may not be optimal in memory-constrained environments. Furthermore, no error checking is implemented, presuming the string operations always succeed.

In C++, the append() method is used to concatenate one string onto another, creating a new string which combines both original strings. For example, calling append() on a string with another string as an argument will result in the original string being extended by the contents of the argument string. The compare() method compares two strings lexicographically and returns an integer: zero if the strings are equal, a positive number if the invoking string is lexicographically greater, and a negative number if it's smaller. These methods are essential for efficient string manipulation.

The code ensures that file operations are reliable by checking if a file opens successfully using the is_open() method before proceeding with any read or write operations. If a file fails to open, an error message is printed to the console, informing the user about the failure. This strategy prevents further operations on an inaccessible file, thus maintaining program stability and reliability.

The ios::trunc mode in C++ file handling opens a file for writing and truncates its content immediately upon opening, effectively clearing the file’s existing contents. This mode is useful when a file's content needs to be entirely replaced. When ios::trunc is used with ios::out, it ensures the file is prepared for new data by removing any previous data.

To read a file character by character in C++, first open the file using an fstream object in input mode (ios::in). After checking if the file has successfully opened, use a while loop with file.get(ch) to read each character individually, where 'ch' is a char variable. In each iteration, output the character, and after reading, close the file using file.close()

The Distance class includes a constructor that takes a float value as input, representing the distance in feet. It converts this value to meters by multiplying the input by 0.3048 (the conversion factor from feet to meters) and then assigns it to the private integer variable 'meters' via a static cast to convert the result to an integer.

You might also like