Adithya Yelloju
Adithya Yelloju

Reputation: 21

how to scan line in c program not from file

How to scan total line from user input with c program?

I tried scanf("%99[^\n]",st), but it is not working when I scan something before this scan statment.It worked if this is the first scan statement.

Upvotes: 2

Views: 10123

Answers (4)

char str[1024];
char *alline = fgets(str, 1024, stdin);
scanf("%[^'\n']s",alline);

I think the correct solution should be like this. It is worked for me. Hope it helps.

Upvotes: -1

chux
chux

Reputation: 154175

How to scan total line from user input with c program?

scanf("%99[^\n]",st) reads a line, almost.

With the C Standard Library a line is

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. C11dr §7.21.2 2

scanf("%99[^\n]",st) fails to read the end of the line, the '\n'.

That is why on the 2nd call, the '\n' remains in stdin to be read and scanf("%99[^\n]",st) will not read it.

There are ways to use scanf("%99[^\n]",st);, or a variation of it as a step in reading user input, yet they suffer from 1) Not handling a blank line "\n" correctly 2) Missing rare input errors 3) Long line issues and other nuances.


The preferred portable solution is to use fgets(). Loop example:

#define LINE_MAX_LENGTH 200
char buf[LINE_MAX_LENGTH + 1 + 1];  // +1 for long lines detection, +1 for \0
while (fgets(buf, sizeof buf, stdin)) {
  size_t eol = strcspn(buf, "\n");  **
  buf[eol] = '\0';  // trim potential \n
  if (eol >= LINE_MAX_LENGTH) {
    // IMO, user input exceeding a sane generous threshold is a potential hack
    fprintf(stderr, "Line too long\n");
    // TBD : Handle excessive long line
  }

  // Use `buf[[]`
}

Many platforms support getline() to read a line.

Short-comings: Non C-standard and allow a hacker to overwhelm system resources with insanely long lines.


In C, there is not a great solution. What is best depends on the various coding goals.


** I prefer size_t eol = strcspn(buf, "\n\r"); to read lines in a *nix environment that may end with "\r\n".

Upvotes: 1

user2371524
user2371524

Reputation:

How to scan total line from user input with c program?

There are many ways to read a line of input, and your usage of the word scan suggests you're already focused on the scanf() function for the job. This is unfortunate, because, although you can (to some extent) achieve what you want with scanf(), it's definitely not the best tool for reading a line.

As already stated in the comments, your scanf() format string will stop at a newline, so the next scanf() will first find that newline and it can't match [^\n] (which means anything except newline). As a newline is just another whitespace character, adding a blank in front of your conversion will silently eat it up ;)

But now for the better solution: Assuming you only want to use standard C functions, there's already one function for exactly the job of reading a line: fgets(). The following code snippet should explain its usage:

char line[1024];
char *str = fgets(line, 1024, stdin); // read from the standard input

if (!str)
{
    // couldn't read input for some reason, handle error here
    exit(1); // <- for example
}

// fgets includes the newline character that ends the line, but if the line
// is longer than 1022 characters, it will stop early here (it will never 
// write more bytes than the second parameter you pass). Often you don't 
// want that newline character, and the following line overwrites it with
// 0 (which is "end of string") **only** if it was there:
line[strcspn(line, "\n")] = 0;

Note that you might want to check for the newline character with strchr() instead, so you actually know whether you have the whole line or maybe your input buffer was to small. In the latter case, you might want to call fgets() again.

Upvotes: 3

torstenvl
torstenvl

Reputation: 785

scanf() should never be used for user input. The best way to get input from the user is with fgets().

Read more: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html

Upvotes: 0

Related Questions