首页 > 解决方案 > 声明为变量的 C++ 字符串与在结构中读取的区别

问题描述

最近,在重新引入 C++ 时,我遇到了一个我编写此代码的练习。

#include<stdio.h>
#include <iostream>
#include<string>

using namespace std;

struct Student {
    string name;
    string address;
    string telephoneNumber;
    float grade1;
    float grade2;
};

string situation;

int main () {
    Student student;
    situation = "failed";
    float media;

    scanf("%s", &student.name);
    scanf("%s", &student.address);
    scanf("%s", &student.telephoneNumber);
    scanf("%f", &student.grade1);
    scanf("%f", &student.grade2);

    average = (student.grade1 + student.grade2) / 2;
    if (average >= 7.0) {
        situation = "pass";
    }
    printf("The average of the student %s is %4.1f\n", &student.name, average);
    printf("And his/her situation is %s\n", situation.c_str());

    system("PAUSE");
    return 0;
}

有谁知道为什么要使用 printf 打印出结构属性 student.name 我不需要使用 .c_str() 并且需要它来打印情况值,如果它们都被声明为字符串,一个在 struct 内部,另一个作为变量。

标签: c++stringstructtypesprintf

解决方案


推荐阅读