Declaring variables as strings

 

As with numbers, you can use strings directly in your program, as follows:


PRINT “Print me.”
PRINT 54
END

Just as with numbers, you may want to store strings in variables so you can reuse that particular string over and over again by typing just the variable rather than the entire string.

Unfortunately, every programming language tends to use different ways to declare a variable to hold a string data type. In Liberty BASIC, you never declare variables until you actually assign data to them. When assigning a string to a variable, the variable name must include the dollar sign ($) at the end of the variable name, as follows:


MyName$ = “Bo the Cat”

In Revolution, you can assign a string to a variable (just like you can assign a number to a variable) by using the into command like so:


put “Bo the Cat” into MyName

In REALbasic, you can declare a variable to hold string data types, as follows:


Dim MyName As String

The C++ language won’t recognize string data types, so you must use a library file called std, which you can include in your program by adding the following:


using namespace std;

This command tells your C++ program to use a library file called std, which defines a string data type. After you include the std library file, you can declare a string variable such as:


string myName;

So an entire C++ program that declares a string variable might look like this:


#include <iostream.h>
#include <stdio.h>
using namespace std;
int main()
{
   string myName;
   myName = “Bo the Cat”;
   cout << myName;
   cout << “\nPress ENTER to continue…” << endl;
   getchar();
   return 0;
}

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply



eXTReMe Tracker