写一个C++代码。声一个void类型函数B,主函数调用B对结构体book赋值,在主程序main中定义结构体bookbook
时间: 2024-05-03 22:20:22 浏览: 9
以下是可以实现你的要求的C代码:
```
#include <stdio.h>
// 定义书籍结构体
struct book {
char title[50];
char author[50];
};
// 声明void类型函数B
void B(struct book *b) {
printf("请输入书名和作者名:\n");
scanf("%s%s", b->title, b->author);
}
// 主函数调用函数B对结构体book赋值
int main() {
struct book book1;
B(&book1);
printf("你输入的书名是:%s\n", book1.title);
printf("你输入的作者名是:%s\n", book1.author);
return 0;
}
```
注意:本AI只是一个语言模型,它不能实际编译和运行代码,上述代码仅供参考。
相关问题
写一个C++代码。在主程序中定义一个结构体book,声明另一个void类型函数B,主函数调用B对结构体book赋值
好的,您可以参考以下代码:
```c
#include <stdio.h>
struct book {
char title[50];
char author[50];
float price;
};
void B(struct book *b) {
printf("Please enter the book title: ");
scanf("%s", b->title);
printf("Please enter the book author: ");
scanf("%s", b->author);
printf("Please enter the book price: ");
scanf("%f", &b->price);
}
int main() {
struct book my_book;
B(&my_book);
printf("Book title: %s\n", my_book.title);
printf("Book author: %s\n", my_book.author);
printf("Book price: $%.2f\n", my_book.price);
return 0;
}
```
在上面的代码中,我们首先定义了一个结构体`book`,包括书名、作者和价格。接着我们声明了一个无返回值、参数为`book*`类型的函数`B`,用于给传入的结构体指针赋值。在`main()`函数中定义了一个名为`my_book`的`book`类型变量,然后调用函数`B`来赋值这个变量。最后打印出这个变量的值。
如何用c++语言来写一个结构体,并在main函数中调用结构体中的函数
可以用以下代码来定义一个结构体,并在main函数中调用结构体中的函数:
```c
#include <stdio.h>
// 定义一个结构体
struct student {
char name[20];
int age;
float score;
};
// 定义一个结构体函数
void printStudentInfo(struct student s) {
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Score: %.2f\n", s.score);
}
int main() {
// 创建一个结构体实例
struct student s1 = {"Tom", 18, 90.5};
// 调用结构体函数
printStudentInfo(s1);
return 0;
}
```
在这个例子中,我们定义了一个名为`student`的结构体,它包含了三个成员变量:`name`、`age`和`score`。我们还定义了一个名为`printStudentInfo`的结构体函数,它接受一个`student`类型的参数,并打印出这个学生的信息。
在`main`函数中,我们创建了一个名为`s1`的`student`类型的实例,并初始化了它的成员变量。然后,我们调用了`printStudentInfo`函数,将`s1`作为参数传入,从而打印出了`s1`的信息。
希望这个例子能够对你有所帮助!