【问题标题】:How to take an array of "strings" and put them into an array of characters in C?如何获取“字符串”数组并将它们放入C中的字符数组中?
【发布时间】:2020-03-29 22:22:15
【问题描述】:

我有一个来自结构的字符数组,它们代表名称。我可以在我的主函数中完美地打印它们,但如果我将它们传递给不同的函数,它们会被读取为整数。如何将相同的值传递给函数并打印出名称?

比如我目前有

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "student_struct.c"

struct Student{
    char name[50];
    int id;
    float gpa;
    int age;
};

int main(){

    FILE *fptr;
    fptr = fopen("student_records.txt", "r");

    struct Student students[100] = {0};

    //Declaring fields
    int i;
    unsigned int counter = 0;

    //Take data from the file
    for( int i = 0; i < 100; i++) {
        if(fscanf(fptr, "%49s %d %f %d",
            students[i].name,
            &students[i].id,
            &students[i].gpa,
            &students[i].age
        ) != 4) {
        break;
    }
        counter++;
    }

    //Creating a new names array to pass through the function
    char names[counter];
    for(i = 0; i < counter; i++){
        names[i] = *students[i].name; 
    //I see that I'm using the asterisk, which I believe is what's giving me 
    //the integer value, but when I delete it, I get an an error
    //that says "assignment makes integer from pointer without a cast"
    }


    //To close the file
    fclose(fptr);

    //Calling function
    calcHighGPA(names, gpas, counter);

    return 0;
}

如代码中所述,我无法将 struct Student 中的“字符串”值放入 char 数组 (names),我一直收到一个整数值。我也尝试简单地将struct student-&gt;name 传递给函数,但这给我留下了同样的问题。如何获取学生的姓名并将其传递给下面的函数?

我试图调用的函数:

void calcHighGPA(char name[], float input[], int count){

    float highestGPA = input[1];
    int i;
    int nameGPA = 0;
    for(i = 0; i < count; i++){
        if(input[i] > highestGPA){
            highestGPA = input[i];
            nameGPA = i;
        }
    }

    printf("Student with the highest GPA: %s of %.1f\n", name[nameGPA], highestGPA);

}

当我调用函数时,printf 行期待一个整数,但我期待一个“字符串”。

如果需要参考,我正在阅读的文本文件:

David 1234 4.0 44
Sally 4321 3.6 21
Bob 1111 2.5 20
Greg 9999 1.8 28
Heather 0000 3.2 22
Keith 3434 2.7 40
Pat 1122 1.0 31
Ann 6565 3.0 15
Mike 9898 2.0 29
Steve 1010 2.2 24
Kristie 2222 3.9 46

感谢您的帮助。

【问题讨论】:

  • names[i] = *students[i].name; 使 names 包含来自每个 student[i].name 字符串的第一个字符。 names 也不是 nul-terminated 并且不能用作字符串。这将是一个简单的字符数组。 name[nameGPA] 是单个字符(它调用 Undefined Behavior 因为"%s" 不匹配name[nameGPA] ...)

标签: c string function integer character


【解决方案1】:

你在 calcHighGPA() 中传递了一个字符串(一个字符数组名称),而我猜你期待一个字符串数组! 在下面的sn -p

char names[counter];
for(i = 0; i < counter; i++){
    names[i] = *students[i].name; 
}

您实际上并没有复制所有名称。相反,您只是复制每个字符串(字符串)的第一个字符!

您在哪里声明和定义传递给 calcHighGPA 的 gpas 数组?

【讨论】:

  • 糟糕,为了清楚起见和更简洁,我将其从帖子中删除。您对如何将每个名称复制到数组中有任何建议吗?我不确定我的问题是什么,所以我不知道要谷歌什么。感谢您的帮助!
  • @help_me 您可以使用strcpymemcpy 将所有名称复制到您的名称数组中,请通过手册页正确使用它们
猜你喜欢
  • 1970-01-01
  • 2018-09-02
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多