I have at least 2 problems with the code but I will start with this one.
The following code does not seem to work correctly:
cout<<"Vill du mata in en post till? (ja/nej)"<<endl; //I'm asking if the user wants to run the for-loop one more time or brake with ja(yes) or nej(no).
cin>>svar;
if (svar == ja)
{
return 0;
}
The problem is that if the user answers no it does not brake but instead runs trough the for-loop without “running” or “executing” the cin>> lines.
I did some troubleshooting and found that if I change if (svar == ja) to if (svar != nej) it brakes the for-loop, but the problem is it does so even if I put in ja(yes) or anything else…
Heres is the full code, thank you for any help you can provide:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct telefonbok
{
string namn;
string nummer;
};
int main()
{
int ja, nej;
telefonbok post[10];
bool svar; //behövs för frågan om man vill fortsätta.
for (int i=0; i<10; i++)
{
cout<<"Lagg till en post i telefonboken."<<endl;
cout<<"Ange personens namn: "<<endl;
cin>>post[i].namn;
cout<<"Ange personens nummer :"<<endl;
cin>>post[i].nummer;
cout<<"Vill du mata in en post till? (ja/nej)"<<endl;
cin>>svar;
if (svar == ja) //stoppar slingan om man svarar nej
{
return 0;
}
}
system("PAUSE");
return 0;
}
Svar should be a string (since you are expecting the user to enter a string “ja” or “nej”, and not an integer which the code expects), and you should probably check for
"nej"instead of"ja"considering the question you ask. If you only want to exit the loop and not the function usebreak: