Question:
How to correctly correct the function for this C++ vector code?
Clare
2013-02-22 08:50:49 UTC
I've done a C++ code to add a letter to a name. For example:
Enter a letter to add: W
Enter the position: 1
Output: WENDY

but the way to do the function is not correctly done as everything is declared globally there is no parameter inside the function. How to correctly correct the function so that value/references could be pass to the main?

Code:
#include
#include
using namespace std;

vector myname;
int i,position;
string letter;

int addLetter()
{
myname.insert(myname.begin() + position-1, letter);

for ( i=0;i {
cout<<" "< }
cout< cout<
}

int main()
{

myname.push_back("E");
myname.push_back("N");
myname.push_back("D");
myname.push_back("Y");

cout<<"Enter a letter to add: ";
cin>>letter;
cout<<"Enter the position: ";
cin>>position;

addLetter();

system ("pause");
return (0);
}

Thx
Three answers:
David
2013-02-22 14:02:18 UTC
Add parameters to the function. The first should be the vector, the second is the letter and the third is the position. The vector should be passed by-reference so that the changes to the parameter affect the actual vector that was passed. For example:



    void addLetter(std::vector &myname, std::string &letter, int position);



[The string was passed by-reference because it is more efficient for the program so as to avoid a copy of large class objects]



This function no longer requires the existence of global variables to operator correctly. You can now move your variables to the local scope of main and pass them to the function like this:



    addLetter(myname, letter, position);
jamila
2016-12-12 12:28:14 UTC
listed proper listed right here are the elementary errors on your code: --------------------------------------..... # incorporate string : it particularly isn't a suited incorporate actuality for string as string is an shopper-defined library. & : it particularly isn't a suited operator. The AND opreator is represented via && . using namespace std : Enclose this indoors of /* or // commentary symbols .
2013-02-26 07:48:04 UTC
just add something to davids answer



why int addLetter(); use void if you are not interested in returning anything!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...