I'd like to put a string from a text file in the array.
char memo[10], name[10], memomon[10], memoday[10], memoname[10][10];
while(fscanf(fp, "%d%d%s%d", &mon, & day, name, & num)!=EOF){
memomon[i] = mon;
memory[i] = day;
memoname[i] = *name;
memo[i] = num;
i++;
}
In this case, how can I put all the strings in the memoname?
c
You don't have to substitute temporary variables in the first place, so if I were you,
inti, memomon[10], memoday[10], memonum[10];
char memoname [10][10];
for(
i = 0;
i<10&fscanf(fp, "%d%d%d%9s%d", & memomon[i], & memoday[i], memoname[i], & memonum[i])==4;
++i
);
I think it will be written as .If you want to use temporary variables, why don't you copy the string with strcpy
?
strcpy(memoname[i], name);
バッファTo prevent buffer overflow, always specify the number of characters in the string format, such as %9s
.
In C language, String (array of char) cannot be substituted (copied) with 代= 演算 operator. You should try the strcpy() function first.
This is a supplement to CertaiN's answer, but the final answer is "I want to put a string in the C language array."
snprintf(buf, sizeof(buf), "%d", mon);
Use snprintf to string.
Array cannot be substituted with =
even now.
However, structures containing arrays can be substituted with =
.
K I couldn't use it when I was in K&R. I think I can do it after ANSI, but I'm not sure.
To be clear, the following method is not the royal road to copy an array.
I thought it might be faster than memcpy, so I compared the performance, and there was no significant difference.
Memcpy was very fast.今 I haven't checked what's going on now.
Array is not a good way to unify the number of elements.
It is standard to use the define constant, but it is difficult not to force it.
You can define it in a header file, but you are reluctant to define the entity in a header file.
If it is a structure, you can declare the number of elements in the array, and you can write it in a header file and share it with it.
=
In this example, array s2 is substituted for s1.
(Note) Non-char arrays are dangerous because alignment is not guaranteed.
#include<stdio.h>
int main(intargc, char*argv[])
{
chars1[1024] = {0};
chars2[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
typeef structure {
chars [1024];
} Txx;
*((Txx*)s1)=*(Txx*)s2); // Replace array with =
printf("s1=[%s]\n",s1);
printf("s2=[%s]\n", s2);
return 0;
}
© 2024 OneMinuteCode. All rights reserved.