c - 为什么我不能将字符串添加到结构中?
问题描述
所以我正在尝试创建一个将数据读入文件的程序。但在此之前,我需要将数据存储到结构中。如何将字符串存储在结构中?
#include <stdio.h>
#define MAX 100
int count;
struct cg {
float price;
char singer, song;
int release;
} hold[100];
int main() {
while (1) {
printf("Name of band of Singer: ");
scanf_s("%s,", &hold[count].singer);
printf("Name of Song: ");
scanf_s("%c", &hold[count].song);
printf("Price: ");
scanf_s("%f", &hold[count].price);
printf("Year of Release: ");
scanf_s("%d", &hold[count].release);
count++;
printf("\n");
}
}
解决方案
由于这里的问题是关于在 a 中存储字符串,所以struct
这是一个简单的解决方案:
#include <stdio.h>
#define MAX 100
int count;
struct cg {
float price;
char singer[20], song[20];
int release;
}hold[100];
int main() {
printf("Name of band of Singer: ");
fgets(hold[0].singer, 20, stdin);
printf("Singer: %s\n", hold[0].singer);
}
这个程序只是演示了在结构中存储一个字符串。这里,是您可以在or中存储20
的最大字符数(包括终止字符) 。或者,您还可以使用要存储的字符串动态分配内存。NUL
singer
song
malloc()
请注意您的程序还有其他几个问题。例如,您的循环永远不会结束并且 a}
丢失了。
推荐阅读
- angular - 如何在从for循环中获取值时将值从html传递到打字稿
- ios - 如何获取表格视图单元格每一行中字符串文本的高度?
- javascript - 如何在不刷新浏览器的情况下获取更改?
- ios - GraphQL 架构文件应包含有效的 GraphQL 自省查询结果
- django - 向 django 发出 axios 请求
- reactjs - 创建 React 应用程序时出现 NPM 和 Yarn Registry 问题
- jenkins - Jenkins 失败的屏幕截图
- ms-access - 用于更改组合框选择的 Win32 API 调用
- asp.net-web-api2 - 在 Web API 中提供 VB.net DLL 参考
- asynchronous - Netty Http 客户端分析。如何计算服务器响应时间?