Can't access my vector variables in different conditions - c++

I'm trying to do creating objects in a one condition and listing this objects in another condition, but it doesn't work.
void fillVector(vector<Account>& newcreateAccObj){
string name;
string password;
cout<<"Enter your surname:"<<endl;
cin>>name;
cout<<"Enter your password:"<<endl;
cin>>password;
Account newAcc(name,password);
newcreateAccObj.push_back(newAcc);
cout<<endl;
}
This works fine.
void printVector(vector<Account>& newcreateAccObj){
unsigned int size=newcreateAccObj.size();
for(unsigned int i=0;i<size;i++){
cout<<"Account"<<i+1<<endl;
cout<<"-----------"<<endl;
newcreateAccObj[i].getId();
newcreateAccObj[i].getName();
cout<<endl;
}
}
This works fine too when I execute these 2 functions in same condition.
But when I do this:
int main(){
int whileCondition=-1;
string girisSecim;
vector<Account> createAccObj;
while(whileCondition==-1){
cout<<"--------------------------------------------------------"<<endl;
cout<<"??????????????????????????????????????????????????????"<<endl;
cout<<"1-create acc 2-transferring"<<endl;
cout<<"3-enter acc 4-exit"<<endl;
cout<<"--------------------------------------------------------"<<endl;
cin>>girisSecim;
if(girisSecim=="1"){
fillVector(createAccObj); //BURDA OBJE OLUSTURULUYOR
}
else if(girisSecim=="2"){
printVector(createAccObj);
}
else if(girisSecim=="3"){
}
else if(girisSecim=="4"){
return 0;
}
else{
cout<<"Hatali tuslama."<<endl;
}
whileCondition=0;
cout<<"Programa devam etmek icin -1'i, cikmak icin herhangi bir seyi tuslayiniz."<<endl;
cin>>whileCondition;
}
Edit: I edited the main part.
I choose option 1 first. I create my object and returning the select menu, after that I choose option 2 and it gives me a blank output.

follow the lifetime of createAccObj.
it seems like you do not send the same vector to both functions.
I will have a guess, your code looks like this:
while (input}(
vector<Account> createAccObj;
if(input=="1"){
fillVector(createAccObj);
}else if(input=="2"){
printVector(createAccObj);
}
here, on each iteration, new vector is created, so when you try to print, you print empty vector.
If this is the case, simply, remove the vector deceleration outside the loop.
Edit:
looking into the code again, seems like you forgot cout in newcreateAccObj[i].getId(); and newcreateAccObj[i].getName();

Related

cout doesn't works properly on my program, can somebody help me?

enter image description hereI am using the STL in c++ and inside a bucle the cout doesn't prints correctly a float.
my program ads values to a vector and then passes it to a function to see if the condition exist, actually it works perfectly but just the cout doesn't word, I already tried using printf() but it gave the same result.
note:please algo give me feedback on my question is the first time i do one and English is not my natal language
my code:
#include<bits/stdc++.h>
#include<vector>
using namespace std;
void isthereanumber(vector<float> array);
int main(){
string ans;vector<float> array;float number;
do{
fflush(stdin);
cout<<"insert a value for the vector: "<<endl;
cin>>number;
array.push_back(number);
fflush(stdin);
cout<<"would you like to keep adding values to the vector? "<<endl;
getline(cin,ans);
}while(ans.compare("yes")==0);
isthereanumber(array);
return 0;
}
void isthereanumber(vector<float> array){
float suma =0;
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+array[*j];
}
}
if(suma=array[*i]){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}
cout<<"there is not a number with such a condition: ";
return;
}
As stated by cleggus already there are some issues present. Those need to be adressed first. After that there's a logical error in that suma just keeps growing.
Given the input 5,5,10 once we test for 10 we would like suma to be set to 0 again for it to work but it will be something like 30 now instead.
That can be solved by moving suma inside the outer loop.
Working example for input 5,5,10: https://godbolt.org/z/gHT6jg
I think you may have a couple of issues...
In your for loops you are creating iterators to the vector, but rather than just dereferencing them to access the indexed element you are dereferencing them and then using that as an index to the same vector.
Also Your last if statement has an assignment = rather than a comparison ==.
I believe this is closer to what you are trying to achieve (sorry I haven't had time to compile and check):
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+*j;
}
}
if(suma==*i){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}

converting string vectors to int

I have to make a program that reads information for a student from a file, and I made a couple of vectors to keep all that information. But then I need to sum up the absences of all the students, so I need to convert them to integer, however when I try to the program runs, but crashes immediately when it reaches the atoi part.
while(!read.eof()) {
if(i==4){
i=0;
}
read>>b;
if(i==0){ names.push_back(b); }
if(i==1){ last_name.push_back(b); }
if(i==2){ absences.push_back(b); }
if(i==3){ unatoned.push_back(b); }
i++;
}
int a = atoi(absences[0].c_str());
If absences remains empty then the behaviour of absences[0] is undefined.
Using absences.at(0) when absences is empty forces the compiler to throw an exception so is easier to work with.
Either way, for the number of absences, use simply
auto a = absences.size();
You should change you absences vector to be a vector of int:
std::vector<int> abscences;
// rest of the code...
The read >> var instruction will take care of the conversion.
Of course, the >> operator will not write into the integer if it's invalid.

C++ Evil Hangman Implementation problems

I'm trying to implement a version of Evil Hangman where the game changes word depending on what is the most difficult to guess. However I'm getting an error and I just can't seem to spot it. It's probably something stupid but it feels like I've been staring at it for hours. I've narrowed it down to this via print statements before it crashes:
vector<string> newWords;
bool inword=false;
int place=0;
cout<<"here 1";
if(!remove){//remove true so only keep words that dont have letter in them.
cout<<" in if(remove) \n";
for(int i=0;i<wordsLeft.size();i++){
cout<<" in first loop \n";
for(int n=0;n<(wordsLeft[i].length())&&!inword;n++){
cout<<"in second loop n: "<<n<<" i: "<<i<<" inword: "<<inword<<" length: "<<wordsLeft[i].length()<<endl;
if(wordsLeft[i].at(n)==letter){
inword=true;
}
}
if(!inword){//if false then add word meaning words not containing letter array
newWords[place]=wordsLeft[i];
place+=1;
}
else{
inword=false;
}
}
cout<<"here 2";
}
else{//remove false so only keep words that have letter in them.
cout<<"here 3";
for(int i=0;i<wordsLeft.size();i++){
for(int n=0;n<(wordsLeft[i].length())&&!inword;n++){
if(wordsLeft[i].at(n)==letter){
inword=true;
}
}
if(inword){//if true then add word meaning words containing letter array
newWords[place]=wordsLeft[i];
place+=1;
inword=false;
}
}
cout<<"here 3.5";
}
cout<<"here 4";
index=place;
wordsLeft=newWords;
}
I can't add comments yet, but based on your comment it's saying that wordsLeft wasn't declared in the scope, that means that wordsLeft in your first for loop is inaccessible. You may have definied that variable elsewhere in another function or it may be private.
Post where wordsLeft was definied and for next time: Post the error message/code

Tennis Score Keeper

I am willing to write a code of a tennis score keeper in C++ that keeps track of the score, but there are 2 problems that occur when I run the program:
I can't quit the loop with while(cin!="q")
The functions wouldn't initialize the variables
#include<iostream>
#include<string>
using namespace std;
int points1=0, points2=0;
int set1=0, set2=0;
int games1=0, games2=0;
string in="";
void score(int point,int set,int game);
int main()
{
do
{
cout<<"POINTS: "<<points1<<":"<<points2<<endl<<"SETS: "<<set1<<":"<<set2<<endl<<"GAMES: "<<games1<<":"<<games2<<endl;
cout<<"Who scored - player 1 or player 2? (p1/p2) : ";
cin>>in;
if(in=="p1")
{
void score(int points1,int set1,int games1);
}
else if(in=="p2")
{
void score(int points2,int set2,int games2);
}
else {cout<<endl<<"Error!"<<endl<<endl;}
}
while(cin!="q");
system("pause");
return 0;
}
void score(int& point,int& set,int& game){
if(set<5)
{
switch(point)
{
case '30':
point=point+10;
case '40':
set++;
point=0;
default:
point=point+15;
}
}
else game++;
}
while(cin!="q");
should be
while(in!="q");
In your function, your switch is on an integer value, so your cases should use an integer value as well:
case '30':
should be
case 30:
The others as well.
This is a function prototype:
void score(int points1,int set1,int games1);
This is a function call:
score(points1,set1,games1);
Make sure you have function calls where you want to execute the function. You have a lot of prototypes where they don't belong.
Some Tennis tips: you need to be two points ahead to win a set, two sets ahead to win a match. You may want to take that into account in your functions. Points and sets of a single player will not be enough to decide who won a set or game.
Edit:
In addition, if you want variables you pass to a function to change outside of this function, you need to pass them by reference.
void score(int& points1, int& set1, int& games1);
Note the ampersands.
Passing parameters to a function will make a [b]copy[/b] of the parameters. This is refered to as pass-by-value, because the value is passed. You can pass-by-reference, which means you don't create a copy but instead pass the location of the actual variable. Changes to it will then be reflected back to your main program.
You want an infinite while loop with a break, also get rid of type defs in function calls -- something like:
while (true) {
cin >> in;
if (in == "p1") {
score(points1, set1, games1);
}
else if (in == "p2") {
score(points2, set2, games2);
}
else if (in == "q") {
break;
} else {
cout << endl << "Error!" << endl << endl;
}
}
The following line is wrong: while(cin!="q");
Instead of cin you need to use in!="q"
The second issue is because you're calling the function in the wrong way.
When you call a function, you just write its name and pass the specified arguments, you don't need to write the function return type when calling it. Also you don't need to specify the types of the arguments you're passing. Your function call should be :
score(points2, set2, games2)
And finally you're switching on an integer, so your cases should check for integers.

Program Crashes when I try to compare two strings in c++?

int removeContact(Contact *newPtr, int runningTotal)
{
//define variables
string remove;
int next;
//prompt user for name they wish to remove
cout << "Enter the name you would like to delete (Last name first): ";
cin.ignore();
getline(cin, remove);
for (int t=0; t<=runningTotal; t++)
{
if (remove.compare(newPtr[t].name) == 0)
{
//calls function moveArrayElements function
moveArrayElements(newPtr, runningTotal, t);
//decrement runningTotal
runningTotal--;
//prompt user contact was found
cout << "Contact was found and deleted!";
next=1;
}
}
if(next!=1)
{
cout<< "ERROR: Contact was not found!";
}
return runningTotal;
}
This function is apart of a larger c++ program that is designed to manage a persons contact information. This function is suppose to remove a contact.
The problem I'm have is with the if (remove.compare(newPtr[t].name) == 0) statement. When my program gets to this part of the code it will crash without giving any errors. I tried straight up comparing both the stings with == operator, but this still results in a crash of my program...
Also, what make this so strange is that this code works perfectly when the function is called while my program is running with the contact that I'm trying to remove not stored in a text file.
However, when I close my program, and load my contact information from the text file, my program will crash... I know that my program is reading the file into the proper string array because I have a print function, so I know that all of my contacts are being transferred into the proper structure arrays...
Any ideas on how I can fix this? Any help would be appreciated! Thanks
UPDATE: I took the suggestions in the comments and changed my for loop to
t<runningTotal;
However, when I do this my program doesn't crash, but it wont's compare the strings...
If runningTotal is the size of your array, then the range of valid elements is [0, runningTotal). In the below code, you're looping up to runningTotal inclusive, when there isn't a valid Contact object there:
for (int t=0; t<=runningTotal; t++)
{
if (remove.compare(newPtr[t].name) == 0)
Therefore when you go and dereference newPtr[t], for t = runningTotal and then try and get the name element, you'll be causing undefined behaviour and may cause a crash.
Try changing t<=runningTotal to t < runningTotal to see if the problem goes away.
Also, is there a reason why you're using arrays as opposed to an std::vector?
i guess the for statement should be:
for (int t=0; t<runningTotal; t++)