指向 C++ 中的结构的指针 - 从控制台读取?

Pointers to structures in C++ - reading from console?

我有一个程序,我想在其中阅读有关书籍的信息,按结构组织 - 例如从控制台阅读作者,然后将其打印在标准输出上,如下所示。然而,Visual Studio 编译器 (IDE) 给出了一个错误 - this declaration has no storage class or type specifier,当我尝试将结构的地址分配给指针时:ptstr = &a; 我想问什么我做错了吗?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Book {
    string title;
    string author;
    string price;

};
Book a;
Book *ptstr;
ptstr = &a;
int main()
{


    cin >> ptstr->author;
    cout << ptstr->author;
    return 0;
}
ptstr = &a;

这是无效的,因为您不能在全局范围内分配给变量。要解决此问题,请将声明更改为:

Book *ptstr = &a;

您也可以将作业移至 main。这里最好的建议是不要使用全局变量并将两个对象移动到 main.

Live Example