Activity 10-3 - Converting Between String Objects and C-Strings



In C++, you can automatically convert and store a C-string in a variable of type string.  Here is an example:

char a_c_string[] = "This is my C-string.";
string string_variable;
string_variable = a_c_string;

cout << string_variable << endl;

This should display: This is my C-string.

This will work fine but you can't convert a string variable to a C-string by going backward, thus,

a_c_string = string_variable;       is ILLEGAL.

Similarly,

strcpy(a_c_string, string_variable);  is also ILLEGAL.

However, the following:

strcpy(a_c_string, string_variable.c_str( ) );    is LEGAL

But, then again, the following:

a_c_string = string_variable.c_str( );       is also ILLEGAL

Reading from files could be sometimes more useful than reading from the keyboard. In a previous lab you have learned how to read from an input file and write into an output file. You also have used an array of characters to store the name of the input or of the output file. We can rewrite that lab using the string class.

Step (1): Include the required directives
#include<fstream>   // This enables you to do file I/O
#include<iostream>  // For cin and cout
#include<cstdlib>   // To use exit(1) that terminates the program
#include<string>   // To use the string class

using namespace std;
Step (2): Create the input/output streams
If fixed file name is used
If file name is an input (file name is not fixed)

 

Create (declare) the streams of type input or output to use them for reading a file or writing to a file.
ifstream inp_stream;    //create an input stream type
ofstream out_stream;  // create an output stream type

(A)
string inp_file, out_file;
(B)
Create (declare) the streams of type input or output to use them for reading a file or writing to a file.
ifstream inp_stream;    //create an input stream type
ofstream out_stream;  // create an output stream type

Step (3): Connect the input stream to an input file/the output stream to an output file
At this point you must be most careful. If, by mistake, you connect an out_stream to an input file, you can destroy the input file.
 
If fixed file name is used
If file name is an input (file name is not fixed)

 
 
 

inp_stream.open("input_file");
if(inp_stream.fail( ))
{
    cout << "Input file opening failed. \n";
    exit(1);   //exit the program
}

Similarly, for an output file we have:
out_stream.open("output_file");
if(out_stream.fail( ))
{
    cout << "Output file opening failed. \n";
    exit(1);   // exit the program
}

(A) 
cout << "Input the name of input file \n";
cin >> inp_file;

(B)
inp_stream.open(inp_file.c_str( ));
if(inp_stream.fail( ))
{
    cout << "Input file opening failed. \n";
    exit(1);   // exit the program
}

Similarly, for an output file we have:
out_stream.open(out_file.c_str( ));
if(out_stream.fail( ))
{
    cout << "Output file opening failed. \n";
    exit(1);   // exit the program
}

If you decide to append to an existing file, use:
outstream.open("output_file", ios::app);

Step (4): Use the input stream to read from the input file/the output stream to write to the output file

To read:
inp_stream >> first_data >> second_data;

To write:
out_stream << first_data << second_data;

Step (5): Close the input and output files by disconnecting the corresponding streams
inp_stream.close( );
out_stream.close( );

 


The following program reads a file containing some integer values (we do not know how many values). It displays the number, the number to the power of two, and the sum up to that point. At last it displays the average of these numbers.

// P10_3. cpp - This program reads some integers from a file and displays:
// The number, number^2, and the sum of all numbers read up to that point
#include<iostream>
#include<fstream>  // Step (1)
#include<cstdlib>
#include<cmath>
#include<string>

using namespace std;

int main( )
{
    int x, count = 0;
    float sum = 0, avg;
    string input_file; // Step (2)-A

    ifstream in_s;  // Step (2)-B - declaration of the stream of type input

    cout << "Please input the input file name \n"; // Step (3)-A Get the file name
    cin >> input_file;

    in_s.open(input_file.c_str( )); // Step (3)-B - connect to the input file and test
    if(in_s.fail( ))
    {
       cout << "Input file opening failed. \n";
       exit(1);  // if we couldn't open the file to read from we exit
    }

    cout << "\t  x \t\t x^2 \t\t Current Sum \n";
    cout << "\t === \t\t === \t\t ========== \n";

    while( in_s >> x) // Step (4)-Read all numbers one-by-one to the end of the file
    {
         sum = sum + x;
         cout << "\t  " << x <<"\t\t  " << pow(static_cast<double>(x),2) << "\t\t  " << sum << "\n";
         count++;
    }

    avg = sum/count;

    cout << "\n \t\t The average of these " << count << " numbers is: " << avg << endl;

    in_s.close( );  // Step (5)-Close the connection (close the file)

   return 0;
}

Exercise 10.3
Use what you have learned from P10_3. cpp to modify the program you have written for the Exercise 10.2 so that your program reads the two lines from an input file and writes the corrected version into an output file. This is the input file you must use for your program. The file contains just a few more lines than your previous example, however the goal is still the same: to replace G++ with g++ and Gcc with gcc. Name this file ex103.cpp.


  Instructions to return your lab to the teacher: (5 points penalty if instructions are not followed appropriately)

  1. Be sure you return all the printed files where you have written all your answers. These are the answers to Ex. 10.1, 10.2, 10.3, and the PostLab.
  2. Transfer ONLY the source files you have written from loki to your local Windows machine and collect them in a  folder called YourLastNameLab10 (ex. AGuercioLab10). Be sure you did not copy any executable file in this folder. If you did, please remove it from the folder.
    The files to be zipped are:

    Exercise 10-1: 
    ex101.cpp
    Exercise 10.2:
    ex102.cpp
    Exercise 10-3:
    ex103.cpp
     

  3. Now exit from the folder, right click on the folder and choose WinZip--> Zip and e-mail. This action will pack your folder and attach it to an e-mail. You can use a Rar Program if you have that program instead of the Zip program.
  4. Send the e-mail to kschaffe@kent.edu with the subject CS23021 Lab 10 Submission.
  5. Send your e-mail before the deadline to receive full credit.

Congratulations! You have completed another Lab of CS I !! :-)