简体   繁体   中英

c++ value losing value after loop

I have the following problem when compiling and executing the following code: inside the while loop, x1 keeps it value. Once "ok" is entered and the while loop is finished, x1 looses its value and is reset to 0.

Can you tell me what causes this?

ps. I know about vectors and tables, but not using them atm. Using dev c++ to compile

int main(){
        int x1 = 10; int x2=10,x3=10;
        int y1=60,y2=20,y3=20;
        string res="";
        cout << "config x pos ";
        cin >> res;
        while(res != "ok"){
            cin >> res;
            x1= atoi(res.c_str());
            moveTo(x1, y1);
            cout << endl;
        }
        cout << x1;
        cout << "config y pos ";
        cin >> res;
        while(res != "ok"){
            cin >> res;
            y1= atoi(res.c_str());
            moveTo(x1, y1);
            cout << endl;
            cout << "x " << x1 << endl;
        }
    }

好的,一旦您输入“ ok”并中断循环,函数atoi(res.c_str())将零返回到变量x1中;

When you enter 'ok' from the console, the next line to execute is

x1 = atoi(res.c_str());

When faced with a non-numeric string, atoi returns 0, which is then assigned to x1. Thus x1 will always be zero when you're loop ends.

I don't know why you do cin >> res twice at the start (once before the loop and then as the first line of the loop copy). Change your loop to:

while ( (cin >> res) && (res != "ok") )
{
    x1= atoi(res.c_str());
    moveTo(x1, y1);
}

You might also want to think about doing something more intelligent than atoi , eg this will just move to 0 if they type in "hello" and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM