简体   繁体   中英

For loop in Visual Studio Pro 2013

I am taking a course on visual C++ and according to the text, the following code should work (exact copy and paste of the text). Intellisense is saying otherwise, claiming there are 5 errors (informing me that cnt2: undeclared identifier, missing ";" before "{" and missing ";" before "}"). I have never attempted this before with any language (quite honestly didn't know it was a possibility), so any enlightening would be appreciated!

#include <iostream>
// Program 2.: Program demonstrates the for-loop.

int main()
{   
    using namespace std;

    for (int cnt1 = 0, int cnt2 = 9; cnt1 < 10; ++cnt1, --cnt2)
    {
        cout << cnt1 << "---Hello, World!---" << cnt2 << endl;
    }
}

Exact text from my book: This time there are two counter variables (separated by commas), which are initialized to 0 and 9. Moreover, one is incremented and the other is decremented. Consequently, as shown from the output, one counts forward and one counts backwards. Part 2-the condition-remains the same; that is, it still specifies that we loop ten times.

What am I doing wrong here? Does visual studio 2013 professional not allow this operation? The text said to use Visual C++ to program, I am just more comfortable with VS.

Your code should be like this

// Program 2.: Program demonstrates the for-loop.

#include <iostream>

int main()
{   
    using namespace std;

    for (int cnt1 = 0, cnt2 = 9; cnt1 < 10; ++cnt1, --cnt2)
    {
        cout << cnt1 << "---Hello, World!---" << cnt2 << endl;
    }
}

errors in your version:

1) You cannot include header-files of standard-library in function-scope (and your include was not properly ended, you forgot '>' symbol).

2) When you declare variables in loop type should be pointed only before first.

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