How do I save a string of indefinite size to a structure?

Asked

Viewed 1,950 times

6

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct Ecoponto{
   int codigo;
   int contentores[3];
   char cidade[20];
   char *rua;
   int nporta;
};


int main(int argc, char** argv) {

   struct Ecoponto ecoponto;
   printf("\nIntroduza o nome da rua:");
   scanf("%s",ecoponto.rua);
   printf("%s",&ecoponto.rua);



   return (EXIT_SUCCESS);
}

I wonder what is the best way to store "the name of the street" with an unknown size in the structure "Ecopoint Ecopoint".

1 answer

3


To save a string of unknown size without spending extra memory, you need to read the street name in a buffer, a very large variable that can support any street name, for example, size 1000. Then use the string library. h and its strlen() function, which returns how many characters a string has and use strlen(buffer).

Now you know how many characters have the street name, if you do

char buffer[1000]; 
scanf("%s", buffer);
int a = strlen(buffer);

You can use the malloc() function of the stdlib. h library to store how much memory you need, for example:

char *nome_rua = (char *)malloc(sizeof(char)*a);

Then you can copy the contents of the buffer to your variable, and use the strcpy() function of the string library. h

Source: https://www.tutorialspoint.com/c_standard_library/string_h.htm

You need to malloc (a+1) positions, because the string must have O, which delimits its end.

And also, you can use the function

char *strncpy(char *dest, const char *src, size_t n)

Because then you would only copy from the buffer the amount of characters read.

  • But using buffer[1000] I am not limiting the string size to 1000?

  • Well, you can put the size of this very large buffer, for example, 10,000. Or go reading char by char, storing in an auxiliary variable (similarly) and controlling how many char’s were read to allocate only the necessary

  • 2

    Allowing unlimited entry is not a good idea. If someone wants to lock your application, you will easily get.

  • Another question is how I pass after the buffer to "Ecoponto.rua" tried with strcpy and did not give and I think it is because the street is as pointing in a structure.

  • It is that if it is probably a school work, it can be chosen a random (but, finite) value. And it can be a test you think about in this case.

  • Thanks.I’ve been able to give it away but when I give a space between the words only copies the first word.

  • It was scanf("%s",buffer);' but this way it no longer copies to the "street".

  • Missing % in scanf("%[ n]s",buffer).

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.