Strings Sample Code

C Strings to Integers

//DISPLAY 8.2 C Strings to Integers 
//Demonstrates the function read_and_clean.
#include <iostream>
#include <cstdlib>
//#include <cctype>

 using namespace std;

void read_and_clean(int& n);
//Reads a line of input. Discards all symbols except the digits. Converts
//the C string to an integer and sets n equal to the value of this integer. 

void new_line( );
//Discards all the input remaining on the current input line.
//Also discards the '\n' at the end of the line.

int main( )
{
   
    int n;
    char ans;
    do
    {
        cout << "Enter an integer and press Return: ";
        read_and_clean(n);
        cout << "That string converts to the integer " << n << endl;
        cout << "Again? (yes/no): ";
        cin >> ans;
        new_line( );
    } while ( (ans != 'n') && (ans != 'N') );
    return 0;
}
//Uses iostream, cstdlib, and cctype:
void read_and_clean(int& n)
{

    const int ARRAY_SIZE = 6;
    char digit_string[ARRAY_SIZE];

    char next;
    cin.get(next);
    int index = 0;
    while (next != '\n')
    {
        if ( (isdigit(next)) && (index < ARRAY_SIZE - 1) )
        {
            digit_string[index] = next;
            index++;
        }
        cin.get(next);
    }
    digit_string[index] = '\0'; //To make the char array a C-string. Otherwisse atoi function may not work properly

    n = atoi(digit_string);  
}

//Uses iostream:
void new_line( )
 {
    char symbol;
    do
    {
        cin.get(symbol);
    } while (symbol != '\n');
}

 

Robust Input Function

//DISPLAY 8.3 Robust Input Function 
//Demonstration program for improved version of get_int.
#include <iostream>
#include <cstdlib>
#include <cctype>

using namespace std;
  
void read_and_clean(int& n);
//Reads a line of input. Discards all symbols except the digits. Converts
//the C string to an integer and sets n equal to the value of this integer. 
void new_line( );
//Discards all the input remaining on the current input line.
//Also discards the '\n' at the end of the line.

void get_int(int& input_number);
//Gives input_number a value that the user approves of.

int main( )
{
  
    int input_number;
    get_int(input_number);
    cout << "Final value read in = " << input_number << endl;
    return 0;
}

//Uses iostream and read_and_clean:
void get_int(int& input_number)
{
    using namespace std;
    char ans;
    do
    {
        cout << "Enter input number: ";
        read_and_clean(input_number);
        cout << "You entered " << input_number
              << " Is that correct? (yes/no): ";
        cin >> ans;
        new_line( );
    } while ((ans != 'y') && (ans != 'Y'));
}
//Uses iostream, cstdlib, and cctype:
void read_and_clean(int& n)
{
      const int ARRAY_SIZE = 6;
    char digit_string[ARRAY_SIZE];

    char next;
    cin.get(next);
    int index = 0;
    while (next != '\n')
    {
        if ( (isdigit(next)) && (index < ARRAY_SIZE - 1) )
        {
            digit_string[index] = next;
            index++;
        }
        cin.get(next);
    }
    digit_string[index] = '\0';

    n = atoi(digit_string);

}

void new_line( )
{
  char symbol;
    do
    {
        cin.get(symbol);
    } while (symbol != '\n');
     
     
}


 

Program Using the Class string

//DISPLAY 8.4 Program Using the Class string 
//Demonstrates the standard class string.
#include <iostream>
#include <string> 
using namespace std;

int main( )
{
    string phrase; 
    string adjective("fried"), noun("ants"); 
    string wish = "Bon appetit!"; 

    phrase = "I love " + adjective + " " + noun + "!";
    cout << phrase << endl
         << wish << endl;

    return 0;
}
 

Program Using the Class string

//DISPLAY 8.5 Program Using the Class string
//Demonstrates getline and cin.get.
#include <iostream>
#include <string> 

void new_line( );

int main( )
{
    using namespace std;

    string first_name, last_name, record_name; 
    string motto = "Your records are our records."; 

    cout << "Enter your first and last name:\n";
    cin >> first_name >> last_name;
    new_line( );

    record_name = last_name + ", " + first_name;
    cout << "Your name in our records is: ";
    cout << record_name << endl;

    cout << "Our motto is\n"
         << motto << endl;
    cout << "Please suggest a better (one-line) motto:\n";
    getline(cin, motto);
    cout << "Our new motto will be:\n";
    cout << motto << endl;

    return 0;
}

//Uses iostream:
void new_line( )
{
    using namespace std;

    char next_char;
    do
    {
        cin.get(next_char);
    } while (next_char != '\n');
}



 

A string Object Can Behave Like an Array

//DISPLAY 8.6 A string Object Can Behave Like an Array
//Demonstrates using a string object as if it were an array.
#include <iostream>
#include <string> 
using namespace std;

int main( )
{
    string first_name, last_name; 

    cout << "Enter your first and last name:\n";
    cin >> first_name >> last_name;

    cout << "Your last name is spelled:\n";
    int i;
    for (i = 0; i < last_name.length( ); i++)
    {
        cout << last_name[i] << " ";
        last_name[i] = '-';
    }
    cout << endl;
    for (i = 0; i < last_name.length( ); i++)
        cout << last_name[i] << " "; //Places a "-" under each letter.
    cout << endl;

    cout << "Good day " << first_name << endl;
    return 0;
}


 

Palindrome Testing Program

//DISPLAY 8.8 Palindrome Testing Program 
//Test for palindrome property.
#include <iostream>
//#include <string>
//#include <cctype>
using namespace std;

void swap(char& v1, char& v2);
//Interchanges the values of v1 and v2.

string reverse(const string& s);
//Returns a copy of s but with characters in reverse order.

string remove_punct(const string& s, const string& punct);
//Returns a copy of s with any occurrences of characters
//in the string punct removed.

string make_lower(const string& s);
//Returns a copy of s that has all uppercase
//characters changed to lowercase, other characters unchanged.

bool is_pal(const string& s);
//Returns true if s is a palindrome, false otherwise.

int main( )
{
    string str;
    cout << "Enter a candidate for palindrome test\n"
         << "followed by pressing Return.\n";
    getline(cin, str);

    if (is_pal(str))
         cout << "\"" << str + "\" is a palindrome.";
    else
         cout << "\"" << str + "\" is not a palindrome.";
    cout << endl;

    return 0;
}

void swap(char& v1, char& v2)
{
    char temp = v1;
    v1 = v2;
    v2 = temp;
}
string reverse(const string& s)
{
    int start = 0;
    int end = s.length( );
    string temp(s);

    while (start < end)
    {
       end--;
       swap(temp[start], temp[end]);
       start++;
    }

    return temp;
}

//Uses <cctype> and <string>
string make_lower(const string& s)
{
    string temp(s); 
    for (int i = 0; i < s.length( ); i++)
        temp[i] = tolower(s[i]);

    return temp;
}

string remove_punct(const string& s, const string& punct)
{
    string no_punct; //initialized to empty string
    int s_length = s.length( );
    int punct_length = punct.length( );

    for (int i = 0; i < s_length; i++)
    {
         string a_char = s.substr(i,1); //A one-character string
         int location = punct.find(a_char, 0);
         //Find location of successive characters
         //of src in punct, starting from the beginning

      if (location < 0 || location >= punct_length)
         no_punct = no_punct + a_char; //a_char not in punct, so keep it
    }

    return no_punct;
}
//uses functions make_lower, remove_punct
bool is_pal(const string& s)
{
    string punct(",;:.?!'\" "); //includes a blank
    string str(s);
    str = make_lower(str);
    string lower_str = remove_punct(str, punct);

    return (lower_str == reverse(lower_str)); //Note that one could use more complicated if-else statement here
}


 
Topic revision: r1 - 2015-10-27 - JimSkon
 
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback