开发者

Why don't structs work in Xcode, when they do in Visual C++? Help needed!

For some reason, this very basic code will compile with no errors in Visual C++, but gives errors in XCode. I will need to know why, in order to continue working in Xcode for my Computer Science class.

#include <iostream>
#include <string>

using namespace std;

struct acct {        // bank account data
    int     num;      // account number
    string name;      // owner of account
    float   balance; // balance in account
};

int main() {

    acct account;

    cout << "Enter new account data: " << endl;
    cout << "Account number: ";
    cin  >> account.num;
    cout << "Account name: ";
    cin  >> account.name;
    cout << "Account balance: ";
    cin  >> account.balance;

    return 0;

}

It gives two errors, one saying that it expected ';' before account (af开发者_如何学运维ter main is declared), and the second that account was not declared for cin >> account.num;


The problem is not actually in your code: while C does require you to prefix your variables with struct in this case, C++ does not. The problem is actually that there is a global function on Unix named acct - it is this that is confusing the compiler. If you renamed your struct to something else, say bank_account, it will behave as you expected.


If you change the "acct account;" in main to "struct acct account;" it should compile. You haven't actually declared a new typedef "acct" in your code, but Visual C++ helpfully does one for you as a non-standard extension. XCode is more strict.

An alternative fix is to do "typedef struct acct { ... } acct;" which will both declare the acct structure and create a new typedef.


I've run into similar problems trying to use a variable named "log."

If you want to keep your structure name, try specifying just the elements you want to use:

using std::cin;
using std::cout;
using std::endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜