Reputation: 339
i have this:
#define TYPESIZE 180
char buff[TYPESIZE];
char dat_nazev[TYPESIZE];
int dat_rok;
And i use this for reading char and int data from text file. I need write them to screen (thats work) and after that use ADD method for adding this to my structure:
int pom = 1;
while(fgets(buff, 1000, fr) != NULL)
{
switch (pom)
{
case 1:
printf ("Nazev: %s", buff);
dat_nazev=buff;
pom++;
break;
case 2:
printf ("Rok vydani: %s", buff);
dat_rok=int(buff);
pom++;
break;
case 3:
printf ("Popis: %s", buff);
dat_popis=buff;
add(dat_nazev, dat_rok, dat_popis);
pom =1;
break;
}
}
But this doesnt work. If i try assign buff to dat_nazev (or anything) this goto fail.
error C2106: '=' : left operand must be l-value
buff and dat_nazev are the same date types...
And dat_rok=int(buff) dont give mi the same value - like 1986 and etc to dat_rok.
Thanks for answers.
Upvotes: 0
Views: 43
Reputation: 25926
To copy strings, you need to use a function like strcpy()
, you can't assign to arrays in C.
For instance:
#include <string.h>
...
case 1:
printf ("Nazev: %s", buff);
strcpy(dat_nazev, buff);
Note that you #define TYPESIZE 180
, but then read in 1,000 characters with fgets()
, so you might read in more data than you have space to store it, which would be bad. strncpy()
is an alternative which lets you put a limit on the number of characters copied, but strncpy()
will not null-terminate the string if it hits the limit, and sometimes (e.g. when using filenames) making only a partial copy of data and then using it can be as bad as having an overflow, so either way you generally need to check your input pretty rigorously and manage your memory carefully.
You also can't convert strings to other types with a cast, in the way that you can with some other higher-level programming languages. You'll need something like strtol()
:
#include <stdlib.h>
...
case 2:
printf ("Rok vydani: %s", buff);
char * endptr;
dat_rok = (int) strtol(buff, &endptr, 10);
if ( *endptr ) {
fputs("Invalid data, not an integer", stderr);
exit(EXIT_FAILURE);
}
String handling is more work in C than it is in some other higher-level languages.
Upvotes: 1