【发布时间】: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->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