c - 将字符串的特定部分转换为整数
问题描述
*更新了我如何将字符串存储到我的结构中
我有一个结构如下:
struct patient {
char name[30], ID[8];
int age, phoneNo;
};
我写了以下代码:
int searchName()
{
char search[30];
char record[60];
const char s[2] = ",";
struct patient c;
char a[8];
int IDno;
FILE* fPtr;
fPtr = fopen("patient.txt", "r");
printf("Enter name to search : ");
getchar();
fgets(search, 30, stdin);
//remove the '\n' at the end of string
search[strcspn(search, "\n")] = 0;
while (fgets(record, 60, fPtr))
{
// strstr returns start address of substring in case if present
if (strstr(record, search))
{
char* pStr = strtok(record, ",");
if (pStr != NULL) {
strcpy(c.ID, pStr);
}
pStr = strtok(NULL, ",");
if (pStr != NULL) {
strcpy(c.name, pStr);
}
pStr = strtok(NULL, ",");
if (pStr != NULL) {
c.age = atoi(pStr);
}
pStr = strtok(NULL, ",");
if (pStr != NULL) {
c.phoneNo = atoi(pStr);
}
}
}
printf("%s", c.ID);
strcpy(a, c.ID);
printf("\n%s", a);
IDno = atoi(a);
printf("\n%d", IDno);
return 0;
}
该代码允许我在文件中搜索字符串,使用 将字符串分成较小的字符串strtok
,然后将它们存储到结构中。假设我在结构中存储了一个字符串“PT3” c.ID
。在我的程序中,我试图将“PT3”字符串从 复制c.ID
到a
,然后使用转换a
为整数。我对此不太确定,但我认为通过将“PT3”转换为整数,只有整数“3”会保留在 中,这正是我想要的。IDno
atoi
atoi
IDno
编辑:问题似乎是我无法使用atoi
. 将不胜感激从“PT3”中获取数字“3”以存储到IDno
.
解决方案
推荐阅读
- java - 如何在一个标签上绘制多个类?(爪哇)
- javascript - WebPack 无法通过本地项目中的命令执行
- c# - 如何使用 XDocument 更新具有命名空间要求的现有 xml 文件?
- java - 某些测试用例的答案是错误的
- java - Java - 当枚举本身可以用作地图时,为什么要使用 EnumMap?
- php - 当我单击提交时,它会打开 php 文件而不是运行它并发送邮件
- c++ - QScroller 禁用动态滚动
- javascript - Javascript Multiple Inputs Value Output
- python - 列表索引超出范围:Python:
- javascript - 将一张图片叠加在另一张图片上