Sunteți pe pagina 1din 3

Search:

Tutorials

Go
C++Language

BasicInput/Output

Notloggedin

register

login

C++
Information
Tutorials
Reference
Articles
Forum

Tutorials
C++Language
AsciiCodes
BooleanOperations
NumericalBases

C++Language
Introduction:
Compilers
BasicsofC++:
Structureofaprogram
Variablesandtypes
Constants
Operators
BasicInput/Output
Programstructure:
Statementsandflowcontrol
Functions
Overloadsandtemplates
Namevisibility
Compounddatatypes:
Arrays
Charactersequences
Pointers
Dynamicmemory
Datastructures
Otherdatatypes
Classes:
Classes(I)
Classes(II)
Specialmembers
Friendshipandinheritance
Polymorphism
Otherlanguagefeatures:
Typeconversions
Exceptions
Preprocessordirectives
Standardlibrary:
Input/outputwithfiles

BasicInput/Output
Theexampleprogramsoftheprevioussectionsprovidedlittleinteractionwiththeuser,ifanyatall.Theysimply
printedsimplevaluesonscreen,butthestandardlibraryprovidesmanyadditionalwaystointeractwiththeuserviaits
input/outputfeatures.Thissectionwillpresentashortintroductiontosomeofthemostuseful.
C++usesaconvenientabstractioncalledstreamstoperforminputandoutputoperationsinsequentialmediasuchas
thescreen,thekeyboardorafile.Astreamisanentitywhereaprogramcaneitherinsertorextractcharacters
to/from.Thereisnoneedtoknowdetailsaboutthemediaassociatedtothestreamoranyofitsinternalspecifications.
Allweneedtoknowisthatstreamsareasource/destinationofcharacters,andthatthesecharactersare
provided/acceptedsequentially(i.e.,oneafteranother).
Thestandardlibrarydefinesahandfulofstreamobjectsthatcanbeusedtoaccesswhatareconsideredthestandard
sourcesanddestinationsofcharactersbytheenvironmentwheretheprogramruns:
stream
description
cin
standardinputstream
cout standardoutputstream
cerr standarderror(output)stream
clog standardlogging(output)stream
Wearegoingtoseeinmoredetailonlycoutandcin(thestandardoutputandinputstreams)cerrandclogarealso
outputstreams,sotheyessentiallyworklikecout,withtheonlydifferencebeingthattheyidentifystreamsforspecific
purposes:errormessagesandloggingwhich,inmanycases,inmostenvironmentsetups,theyactuallydotheexact
samething:theyprintonscreen,althoughtheycanalsobeindividuallyredirected.

Standardoutput(cout)
Onmostprogramenvironments,thestandardoutputbydefaultisthescreen,andtheC++streamobjectdefinedto
accessitiscout.
Forformattedoutputoperations,coutisusedtogetherwiththeinsertionoperator,whichiswrittenas<<(i.e.,two
"lessthan"signs).
1cout << "Output sentence"; // prints Output sentence on screen
2cout << 120;
// prints number 120 on screen
3cout << x;
// prints the value of x on screen

The<<operatorinsertsthedatathatfollowsitintothestreamthatprecedesit.Intheexamplesabove,itinsertedthe
literalstringOutput sentence,thenumber120,andthevalueofvariablexintothestandardoutputstreamcout.
Noticethatthesentenceinthefirststatementisenclosedindoublequotes(")becauseitisastringliteral,whileinthe
lastone,xisnot.Thedoublequotingiswhatmakesthedifferencewhenthetextisenclosedbetweenthem,thetext
isprintedliterallywhentheyarenot,thetextisinterpretedastheidentifierofavariable,anditsvalueisprinted
instead.Forexample,thesetwosentenceshaveverydifferentresults:
1cout << "Hello"; // prints Hello
2cout << Hello;
// prints the content of variable Hello

Multipleinsertionoperations(<<)maybechainedinasinglestatement:
cout << "This " << " is a " << "single C++ statement";

ThislaststatementwouldprintthetextThis is a single C++ statement.Chaininginsertionsisespeciallyusefulto


mixliteralsandvariablesinasinglestatement:
cout << "I am " << age << " years old and my zipcode is " << zipcode;

Assumingtheagevariablecontainsthevalue24andthezipcodevariablecontains90064,theoutputoftheprevious
statementwouldbe:
I am 24 years old and my zipcode is 90064
Whatcoutdoesnotdoautomaticallyisaddlinebreaksattheend,unlessinstructedtodoso.Forexample,takethe
followingtwostatementsinsertingintocout:
cout<<"Thisisasentence."
cout<<"Thisisanothersentence."
Theoutputwouldbeinasingleline,withoutanylinebreaksinbetween.Somethinglike:
This is a sentence.This is another sentence.
Toinsertalinebreak,anewlinecharactershallbeinsertedattheexactpositionthelineshouldbebroken.InC++,a
newlinecharactercanbespecifiedas\n(i.e.,abackslashcharacterfollowedbyalowercasen).Forexample:
1cout << "First sentence.\n";
2cout << "Second sentence.\nThird sentence.";

Thisproducesthefollowingoutput:
First sentence.
Second sentence.
Third sentence.

Alternatively,theendlmanipulatorcanalsobeusedtobreaklines.Forexample:
1cout << "First sentence." << endl;
2cout << "Second sentence." << endl;

Thiswouldprint:
First sentence.
Second sentence.
Theendlmanipulatorproducesanewlinecharacter,exactlyastheinsertionof'\n'doesbutitalsohasanadditional
behavior:thestream'sbuffer(ifany)isflushed,whichmeansthattheoutputisrequestedtobephysicallywrittento
thedevice,ifitwasn'talready.Thisaffectsmainlyfullybufferedstreams,andcoutis(generally)notafullybuffered
stream.Still,itisgenerallyagoodideatouseendlonlywhenflushingthestreamwouldbeafeatureand'\n'whenit
wouldnot.Bearinmindthataflushingoperationincursacertainoverhead,andonsomedevicesitmayproducea
delay.

Standardinput(cin)
Inmostprogramenvironments,thestandardinputbydefaultisthekeyboard,andtheC++streamobjectdefinedto
accessitiscin.
Forformattedinputoperations,cinisusedtogetherwiththeextractionoperator,whichiswrittenas>>(i.e.,two
"greaterthan"signs).Thisoperatoristhenfollowedbythevariablewheretheextracteddataisstored.Forexample:
1int age;
2cin >> age;

Thefirststatementdeclaresavariableoftypeintcalledage,andthesecondextractsfromcinavaluetobestoredin
it.Thisoperationmakestheprogramwaitforinputfromcingenerally,thismeansthattheprogramwillwaitforthe
usertoentersomesequencewiththekeyboard.Inthiscase,notethatthecharactersintroducedusingthekeyboard
areonlytransmittedtotheprogramwhentheENTER(orRETURN)keyispressed.Oncethestatementwiththe
extractionoperationoncinisreached,theprogramwillwaitforaslongasneededuntilsomeinputisintroduced.
Theextractionoperationoncinusesthetypeofthevariableafterthe>>operatortodeterminehowitinterpretsthe
charactersreadfromtheinputifitisaninteger,theformatexpectedisaseriesofdigits,ifastringasequenceof
characters,etc.
1// i/o example
Please enter an integer value: 702
2
The value you entered is 702 and its double is 1404.Edit
3#include <iostream>
4using namespace std;
5
6int main ()
7{
8 int i;
9 cout << "Please enter an integer value: ";
10 cin >> i;
11 cout << "The value you entered is " << i;
12 cout << " and its double is " << i*2 << ".\n";
13 return 0;
14}

Asyoucansee,extractingfromcinseemstomakethetaskofgettinginputfromthestandardinputprettysimpleand
straightforward.Butthismethodalsohasabigdrawback.Whathappensintheexampleaboveiftheuserenters
somethingelsethatcannotbeinterpretedasaninteger?Well,inthiscase,theextractionoperationfails.Andthis,by
default,letstheprogramcontinuewithoutsettingavalueforvariablei,producingundeterminedresultsifthevalueof
iisusedlater.
Thisisverypoorprogrambehavior.Mostprogramsareexpectedtobehaveinanexpectedmannernomatterwhatthe
usertypes,handlinginvalidvaluesappropriately.Onlyverysimpleprogramsshouldrelyonvaluesextracteddirectly
fromcinwithoutfurtherchecking.Alittlelaterwewillseehowstringstreamscanbeusedtohavebettercontrolover
userinput.
Extractionsoncincanalsobechainedtorequestmorethanonedatuminasinglestatement:
cin >> a >> b;

Thisisequivalentto:
1cin >> a;
2cin >> b;

Inbothcases,theuserisexpectedtointroducetwovalues,oneforvariablea,andanotherforvariableb.Anykindof
spaceisusedtoseparatetwoconsecutiveinputoperationsthismayeitherbeaspace,atab,oranewlinecharacter.

cinandstrings
Theextractionoperatorcanbeusedoncintogetstringsofcharactersinthesamewayaswithfundamentaldata
types:
1string mystring;
2cin >> mystring;

However,cinextractionalwaysconsidersspaces(whitespaces,tabs,newline...)asterminatingthevaluebeing
extracted,andthusextractingastringmeanstoalwaysextractasingleword,notaphraseoranentiresentence.
Togetanentirelinefromcin,thereexistsafunction,calledgetline,thattakesthestream(cin)asfirstargument,
andthestringvariableassecond.Forexample:
1// cin with strings
2

What's your name? Homer Simpson

3#include <iostream>
4#include <string>
5using namespace std;
6
7int main ()
8{
9 string mystr;
10 cout << "What's your name? ";
11 getline (cin, mystr);
12 cout << "Hello " << mystr << ".\n";
13 cout << "What is your favorite team? ";
14 getline (cin, mystr);
15 cout << "I like " << mystr << " too!\n";
16 return 0;
}

Hello Homer Simpson.


What is your favorite team? The Isotopes
I like The Isotopes too!

Noticehowinbothcallstogetline,weusedthesamestringidentifier(mystr).Whattheprogramdoesinthesecond
callissimplyreplacethepreviouscontentwiththenewonethatisintroduced.
Thestandardbehaviorthatmostusersexpectfromaconsoleprogramisthateachtimetheprogramqueriestheuser
forinput,theuserintroducesthefield,andthenpressesENTER(orRETURN).Thatistosay,inputisgenerallyexpected
tohappenintermsoflinesonconsoleprograms,andthiscanbeachievedbyusinggetlinetoobtaininputfromthe
user.Therefore,unlessyouhaveastrongreasonnotto,youshouldalwaysusegetlinetogetinputinyourconsole
programsinsteadofextractingfromcin.

stringstream
Thestandardheader<sstream>definesatypecalledstringstreamthatallowsastringtobetreatedasastream,and
thusallowingextractionorinsertionoperationsfrom/tostringsinthesamewayastheyareperformedoncinand
cout.Thisfeatureismostusefultoconvertstringstonumericalvaluesandviceversa.Forexample,inordertoextract
anintegerfromastringwecanwrite:
1string mystr ("1204");
2int myint;
3stringstream(mystr) >> myint;

Thisdeclaresastringwithinitializedtoavalueof"1204",andavariableoftypeint.Then,thethirdlineusesthis
variabletoextractfromastringstreamconstructedfromthestring.Thispieceofcodestoresthenumericalvalue
1204inthevariablecalledmyint.
1// stringstreams
Enter price: 22.25
2#include <iostream>
Enter quantity: 7
3#include <string>
Total price: 155.75
4#include <sstream>
5using namespace std;
6
7int main ()
8{
9 string mystr;
10 float price=0;
11 int quantity=0;
12
13 cout << "Enter price: ";
14 getline (cin,mystr);
15 stringstream(mystr) >> price;
16 cout << "Enter quantity: ";
17 getline (cin,mystr);
18 stringstream(mystr) >> quantity;
19 cout << "Total price: " << price*quantity << endl;
20 return 0;
21}

Inthisexample,weacquirenumericvaluesfromthestandardinputindirectly:Insteadofextractingnumericvalues
directlyfromcin,wegetlinesfromitintoastringobject(mystr),andthenweextractthevaluesfromthisstringinto
thevariablespriceandquantity.Oncethesearenumericalvalues,arithmeticoperationscanbeperformedonthem,
suchasmultiplyingthemtoobtainatotalprice.
Withthisapproachofgettingentirelinesandextractingtheircontents,weseparatetheprocessofgettinguserinput
fromitsinterpretationasdata,allowingtheinputprocesstobewhattheuserexpects,andatthesametimegaining
morecontroloverthetransformationofitscontentintousefuldatabytheprogram.
Previous:
Operators

Index

Homepage|Privacypolicy
cplusplus.com,20002015Allrightsreservedv3.1
Spottedanerror?contactus

Next:
Statementsandflowcontrol

Edit

S-ar putea să vă placă și