#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void)
{
int menuswitch=1;
int amountofstudents;
int fname[50];
int lname[50];
int grade[50];
int i;
char studentinfo[100];
printf("Enter Amount of Students: ");
scanf("%d", &amountofstudents);
for (i=0;i<amountofstudents;i++)
{
gets(studentinfo);
strcpy(fname[i], strtok(studentinfo, " "));
strcpy(lname[i], strtok(NULL, " "));
strcpy(grade[i], strtok(NULL, " "));
}
好吧,需要一点使用 strtok 的能力。我正在尝试存储输入字符串的各个部分以便稍后排序。我正在考虑使用 strtok 来断开字符串,然后将每个片段放入相应的数组中。然而,每次我尝试时,我都会在 Visual Studios 中收到一条错误消息,提示“访问冲突”。感谢您提前提供帮助
错误是
First-chance exception at 0x5120F7B3 (msvcr110d.dll) in Lab 2.exe: 0xC0000005: Access violation reading location 0x00000000.
Unhandled exception at 0x5120F7B3 (msvcr110d.dll) in Lab 2.exe: 0xC0000005: Access violation reading location 0x00000000.
输入内容为
FirstName Lastname 80(Grade)
最佳答案
一个主要问题是您尝试复制到整数值而不是字符串。改变 整数数组到字符串数组:
...
char fname[50][100];
char lname[50][100];
char grade[50][100];
...
<小时/>
您还遇到了 gets
函数的问题(除了它已被废弃且不应使用),即前面的 scanf
不会从输入缓冲区,因此第一个 gets
调用将看到这个空换行符并为您提供一个空行(您无需检查)。
这可以通过告诉 scanf
通过在格式字符串中的 "%d"
之后添加一个空格来丢弃尾随空白来解决:
scanf("%d ", &amountofstudents);
/* ^ */
/* | */
/* Note space */
您应该使用 fgets
而不是 gets
:
fgets(studentinfo, sizeof(studentinfo), stdin);
最后,始终检查错误!
关于c - 使用 Strtok 存储字符串片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19373559/