Why doesn't this work?

#include <stdafx.h> 
#include <iostream>
#include <string>
using namespace std;


int main(){
	static int x;
                int y;
	cout <<"1. view\n2. edit\n";
	cin >> y;
	if (y==1){
		cout <<endl << x <<endl<<endl;
	}
	if (y==2){
		cout <<"Please enter the value of x\n";
		cin >> x;
		cout << "\nx = "<<x<<endl<<endl;
	}


return 0;
}

Recommended Answers

All 5 Replies

>Why doesn't this work?
It works as intended, what did you expect it to do?

If you select 1 without first setting x with 2, you may receive unexpected results.

You haven't told us what's not working correctly, and I'm going to go ahead and assume that you want the variable x to retain its value even after the program closes. This is not what the static keyword does. A static variable simply retains its value even if the function it's called in ends. For example:

int GetNum()
{
    static int x = 0;
    return ++x;
}

int main()
{
    for(int i = 0; i < 100;i++)
        cout << GetNum() <<endl;

    return 0;
}

This will print out the numbers 1-100.

Also, if you're program isn't displaying any results after you give it input, it may be because you don't have system("PAUSE"); before return 0; (assuming you're running Windows).

How do you make the value stay every time you run the .exe?

How do you make the value stay every time you run the .exe?

Write the value to a file. Read from the file using an ifstream at the beginning of the program. If the value changes during the program, write that new value to the file using an ofstream before the program ends. What exactly are you trying to do here?

Save a variable so it is the same evey time you run the program. I'll check out the ofstream thing.
I'm making a password keeper.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.