![]() |
IntroductionWe have been dealing a lot with outputting information to the console. You may find the need to record user input. This will be discussed in this tutorial. Input can be accomplished by using the scanf function for C or the cin object for C++. Contents of main.cpp : #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int main() { The name array will be used to store input as a string and the age variable will be used to store integers. You need to give the string sufficient space to accept the input. The program in this case will therefore not accept input greater than 50 characters. char name[50]; int age = 0;
The scanf function takes parameters as follows : // C Section //----------- printf("Please enter your first name : "); scanf("%s", name); printf("Please enter your age : "); scanf("%d", &age); printf("Thank you %s. You are %d years old.\n", name, age);
The cin object is used the same way as the
cout object but instead of using the << operator,
you use the >> operator. // C++ Section //------------- cout << "Please enter your first name : "; cin >> name; cout << "Please enter your age : "; cin >> age; cout << "Thank you " << name << ". You are " << age << " years old." << endl; system("pause"); return 0; }
Congratulations. You should now be able to accomplish basic input. You may notice
that if you type in a string containing a space, an error may occur. If you type in
eg. "Bob 52", you will enter information for both
fields. Please let me know of any comments you may have : Contact Me
All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005 Read the Disclaimer |
|