1

need string lenght for my scanf , how do i determine what number to put betwen [], can use A[strlen].

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

int main()
{
    char A[];
    printf("enter a string");
    scanf("%s", A);
    printf("%s", A);
    getch();

}
Mohamed Belkamel
  • 359
  • 1
  • 2
  • 8
  • You can’t. That’s the fun of handling open-ended user input. What happens if someone pastes three gigabytes worth of text into their terminal-emulator? – Dai Dec 22 '18 at 12:49
  • 1
    No. If you want to have an *exact* length for `A`, then you first need *another* array in which *any* length of text can be entered, so you can measure it. – Jongware Dec 22 '18 at 12:50
  • why you didn't try to use `char *A`? – Julian Dec 22 '18 at 12:50
  • @Jin: because that leads to a compiler warning ("use of an uninitialized variable"), and ignoring that will lead to a seg fault. Or, possibly worse: it *may* run. Or it may not. – Jongware Dec 22 '18 at 12:56
  • so should i just insert a random number and that's it? – Mohamed Belkamel Dec 22 '18 at 12:58
  • Possible duplicate of [How can I read an input string of unknown length?](https://stackoverflow.com/questions/16870485/how-can-i-read-an-input-string-of-unknown-length) – Jongware Dec 22 '18 at 13:33
  • can't be done with scanf, but scanf can be used only for string(input without white space & new line chars) not for text, usually setting terminal line length(mostly 80 chars) will cover all use cases. – ShivYaragatti Dec 22 '18 at 15:40

1 Answers1

1

Only you can know what length is sufficient for your needs.

If there is a limited set or range of valid inputs, you can use the length of the maximum valid input + 1.

If there isn't a limit to the maximum valid input, either you need to decide that your program doesn't support input longer than X and set that as the limit, or implement reading in a loop into a dynamically growing buffer (e.g., using realloc as needed).

And always remember to limit the maximum allowed input length when reading, so that it's not possible to overflow your buffer with excessive input. (Using fgets is often the simplest to get right.)

Arkku
  • 41,011
  • 10
  • 62
  • 84