c - 使用 Strtok 存储字符串片段

标签 c arrays string strtok

#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/

相关文章:

string - 使用一些字符串形成给定模式的算法

string - 你如何检查字符串是否以 Ada 中的另一个字符串结尾?

c - 如何仅计算列表中以大写字母开头的单词?

c - 如何按 C 中的子午线(AM 和 PM)排序?

c - 难以理解循环

c# - 以字符串为索引点的 3 维数组 c#

c - 使用 poll/select 一次读取一个字节

arrays - 如何连续重复一系列操作中的一个操作

javascript - React Array Prop 在渲染时发生变化

SQL查询多行列中字符串的串联