Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scanf full sentence in C

Tags:

c

string

scanf

How to scanf() full sentence in C without using fgets() or gets()

I want to scan a command line from the user and based on the first word recognize the command. For example: mkdir

so I need to recognize that the user wants to create a new dir with the name "dir_name".

My code:

int main(){
  char *ch=malloc(sizeof("50");
  while (strcmp(ch,"exit")!=0){
     scanf("%[^\n]",ch);
  } 

when i ran this code after i input the first sentence and press enter it went to infinity loop i don't know why?

like image 949
Dkova Avatar asked Dec 15 '22 06:12

Dkova


2 Answers

Your problem is most likely here:

char *ch=malloc(sizeof("50");

To begin with, you're missing one close parentheses. But assuming that this was a typo in posting the question and not in your actual code, there is a deeper issue.

"50" inside double quotes is a string literal. When sizeof() is applied to the string literal, you're going to get the number of characters in the string, including terminating NUL. So you are only allocating space for three characters in ch.

When you try to scanf() the input, you're writing past the end of your three-character buffer ch. Leave out sizeof() and simply say:

char* ch = malloc (50);

Also, the scan set %[^\n] does not skip leading whitespace. Your first scanf() will stop at the newline, which will remain in the buffer. Subsequent scanf() calls in your while loop will encounter that newline character and dutifully stop, as it's excluded from your scan set. So the loop condition

while (strcmp (ch, "exit"))

will never become true, and you'll get an infinite loop. Consume the newline after the scanf() to avoid this problem:

scanf ("%[^\n]%*c", ch);

The %*c means "read a character and then discard it." So it will read the \n that is left in the buffer, and then not save it anywhere. Your next scanf() will therefore not encounter a \n at the beginning of the buffer, and your program will work as you intend.

like image 62
verbose Avatar answered Jan 12 '23 03:01

verbose


#include<stdio.h>
int main()
{
    char  input_string[100];
    scanf("%[^\n]s",&input_string);
    printf("Hello ,world.\n");
    printf("%s",input_string);
    return 0;
}
like image 37
Humayun Kabbya Avatar answered Jan 12 '23 01:01

Humayun Kabbya