今天我试图对 char * 字符串友好...但似乎我失败了:) 每次我调用 strcmp/strncmp/strcpy 函数时,我的源都会损坏...
这是片段
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int UID;
char name[20];
char surname[20];
};
char * getString(int minChars, int maxChars);
struct student * myStud;
int main(int argc, char** argv) {
myStud = (struct student*)malloc(sizeof(struct student));
while(1)
{
printf("\nEnter new name: ");
strcpy(myStud->name,getString(1,19));
printf("\n The values is now %s",myStud->name);
}
return (EXIT_SUCCESS);
}
char * getString(int minChars, int maxChars)
{
char string[maxChars+1];
scanAgain:
scanf("%s",&string);
if(strlen(string)<minChars)
{
printf("\nToo few symbols, try again: ");
goto scanAgain;
}
if(strlen(string)>maxChars)
{
printf("\nToo many symbols, try again: ");
goto scanAgain;
}
string[maxChars]='\0';
return(string);
}
输出:
Enter new name: Alekasdasd
The values is now Alekasda�#
Enter new name:
我只是一个初学者,所以它可能非常简单......可能不是。哦,顺便说一句,使用 linux 和 netbeans 作为 SDK,gcc 作为编译器。