How to Make a String of Asterisks in C++

How to Make a String of Asterisks in C++ thumbnail
Make a string of asterisks.

The C++ programming language stores and manipulates strings as arrays of characters. You can think of a string in C++ as an ordered list of individual characters. This may seem a bit awkward for programmers accustomed to simply declaring a string type in other languages. However, treating each character as a discrete rather than a part of a whole allows much finer control when parsing and manipulating strings. Declare an array of characters, and assign each member the value of "*" to create a string of asterisks.

Instructions

    • 1

      Declare and initialize an array of characters. For this example, use the following code:

      char astString[]

    • 2

      Assign the value of "*" to the individual array members. Building on the code in step one:

      char astString[] = {'*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*',0};

      This statement creates a character array of 11 asterisks. The zero at the end of the statement is used by C++ to indicate the end of the array.

    • 3

      Display the string to the screen with the following example:

      showString(astString);

    • 4

      Write showString as a separate function. This is a simple way to display the members of the array:

      void showString(char astString[])

      {

      for (int i = 0; astString[i] != '\0'; i++)

      {

      cout<< astString[i];

      }

      }

      This simple loop steps through the array and prints each member to the screen. The function terminates when it encounters the '0' character at the end of the array.

Tips & Warnings

  • The code, in the context of a program, looks like this:

  • int main()

  • {

  • char astString[] = {'*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*',0};

  • showString(astString);

  • return 0;

  • }

  • void showString(char astString[])

  • {

  • for (int i = 0; astString[i] != '\0'; i++)

  • {

  • cout<< astString[i];

  • }

  • }

Related Searches:

References

  • Photo Credit Comstock Images/Comstock/Getty Images

Comments

Related Ads

Featured