Compiler ignoring subsequent commands - c

I have the following C code:
#include <stdio.h>
int main()
{
char* ptr;
printf("Enter the word: ");
gets(ptr);
printf("The input string is: ");
puts(ptr);
return 0;
}
It compiles and asks for the input, but after I enter the input, it takes a pause and exits. No further commands are executed or displayed. I am unable to understand the problem. Please help.

#include <stdio.h>
int main()
{
char str[100] = "";
printf("Enter the word: ");
fgets(str, sizeof str, stdin);
printf("The input string is: ");
printf("%s", str);
return 0;
}
Try to use fgets(). gets() is dangerous to use because gets() is inherently unsafe, because it copies all input from STDIN to the buffer without checking size. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition.
puts is simpler than printf but be aware that the former automatically appends a newline. If that's not what you want, you can fputsyour string to stdout or use printf.

Related

using malloc for char variable can not take input data character

I am trying to implement DMA for char variable. But I am unable to take input. I tried with all the possible cases I know:
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
But I can't even enter input data for the character variable ptr_name. I want to take input as "string with space" as input value. How to solve this problem?
And then how to print the entered name in the screen?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
ptr_name = (char*)malloc(name);
printf("Enter name: ");
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
scanf("%d", ...) does not consume the enter so the next scanf() gets an empty string.
you can use getchar() to consume the enter.
Also, you need to allocate additional byte for the zero at the end of the string / string terminator. See the + 1 in malloc().
As for your questions, your commented scanf() had & before argument 2 which isn't expected (char ** vs. char *) but other than that it will allow spaces in strings. puts() will print the entered name, alternatively you can modify the above printf() to print the name, e.g: printf("\n Your name is: %s", ptr_name);
Lastly, please consult Specifying the maximum string length to scanf dynamically in C (like "%*s" in printf) for dynamically limiting the input size, avoiding buffer overflow.
DISCLAIMER: The following is only "make it work" version of the program above and is not intended for real life use without appropriately checking return codes and limiting the input size:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
getchar();
ptr_name = (char*)malloc(name + 1);
printf("Enter name: ");
scanf("%[^\n]", ptr_name);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
if you want to get input with spaces you need to use getline():
getline(&buffer,&size,stdin);
here an example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int len;
printf("Enter number of characters for Name: ");
scanf("%d",&len);
ptr_name = (char*)malloc(len);
printf("Enter name: ");
getline(&ptr_name, &len, stdin);
printf("\n Your name is: %s", ptr_name);
free(ptr_name);
return 0;
}

How can I put a user input value into strncpy?

So, I am trying to write an strncpy function. I want user to input the number of characters to be copied from source. I am doing something wrong, but I can't understand what. This is what I tried to do:
#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20
int main() {
char string[ARR_SIZE];
int n, m;
char s1[4], s2[4], nstr[m];
printf("Enter the string:");
gets(string);
printf("The length of the string is: %ld\n", strlen(string));
strcpy(s1, s2);
printf("The original string is: %s\n", string);
printf("The copy of the original string is: %s\n", string);
printf("How many characters do you want to take from this string to create another string? Enter: \n");
scanf("%d", &n);
strncpy(nstr, s1, m);
printf("%s\n", nstr);
}
(On top I tried some strlen and strcpy functions.)
EDIT: I totally forgot to write what was the problem. Problem is I can't get the new string which is named nstr in my code. Even though I printed it out.
first of all, the whole code is just a bad practice.
Anyway, here is my take on your code which copies n characters of an input string to string_copy
#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20
int main() {
char string[ARR_SIZE];
int n;
printf("Enter the string:");
gets(string);
printf("The length of the string is: %ld\n", strlen(string));
printf("The original string is: %s\n", string);
printf("How many characters do you want to take from this string to
create another string? Enter: \n");
scanf("%d", &n);
if(n > strlen(string)){
n = strlen(string);
printf("you are allowed to copy maximum of string length %d\n", n);
}
char string_copy[n];
strncpy(string_copy, string, n);
printf("%s\n", string_copy);
}
note that using deprecated functions such as gets() isn't safe. use scanf() or fgets() instead.
refer to why you shouldn't use gets()

C function (fgets) mitigation

I can't understand why taking the input using fgets always gives me "Wrong password" for my program.
However, when I use gets(), like gets(array); it works.
Expected outputs: when the password is wrong, prints "Wrong Passwor" and for correct one, let me see my "access is granted":
#include <stdio.h>
#include <string.h>
int main(void)
{
int n=15;
char array[n];
int pass = 0;
printf("\n Enter the password : \n");
fgets(array, n, stdin);
if(strncmp(array, "password",n))
{
printf ("\n Wrong Password \n");
}
else
{
printf ("\n Correct Password \n");
pass = 1;
}
if(pass)
{
/* Now Give root or admin rights to user*/
printf ("\n Root privileges given to the user \n");
}
return 0;
}
The point here is, fgets() reads and stores the trailing newline, check the man page for fgets().
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. [...]
You need to remove that trailing newline before the comparison.
You can sanitize the input, using
array[strcspn(array, "\n")] = 0;
to remove the trailing newline from the input.

unable to take two input strings in C on Ubuntu

I am unable to take two inputs strings simultaneously in C on Ubuntu. It shows the wrong output.
Simple program:
#include <stdio.h>
main()
{
char s1[20],char s2[20],printf("\nEnter job:");
scanf("%[^\n]s",s1);
printf("Enter hobby:");
scanf("%[^\n]s",s2);
}
Output:
Enter job:student
Enter hobby:
student
It does not allow the input of a second string. How can I overcome this bug?
If you want to allow embedded spaces, modify the scanf formats this way:
#include <stdio.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
scanf("%99[^\n]%*c", job);
printf("Enter hobby:");
scanf("%99[^\n]%*c", hobby);
printf("%s,%s", job, hobby);
return 0;
}
But be aware that empty lines will not be accepted by this scanf format. The linefeed will stay in the input stream, the second scanf will fail too and job and/or hobby will have indeterminate contents, letting printf invoke undefined behavior.
Is is much more reliable to use fgets() and strip the '\n'.
#include <stdio.h>
#include <string.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
if (!fgets(job, sizeof job, stdin))
return 1;
job[strcspn(job, "\n")] = '\0';
printf("Enter hobby:");
if (!fgets(hobby, sizeof hobby, stdin))
return 1;
hobby[strcspn(hobby, "\n")] = '\0';
printf("%s,%s", job, hobby);
return 0;
}

How to copy a sentence into a char array

I am trying to copy a sentence into a char array. I have tried using scanf("%[^\n]) and scanf("%[^\n]\n within an if statement but it doesn't work. Can someone please help me figure it out? I am using C language. It works with the first code but not the second.
File #1
#include <stdio.h>
int main ()
{
char c[10];
printf ("Enter text.\n");
scanf("%[^\n]", c);
printf ("text:%s", c);
return 0;
}
File #2
#include <stdio.h>
#include <string.h>
int main(void)
{
char command[10];
char c[10];
printf("cmd> ");
scanf( "%s", command);
if (strcmp(command, "new")==0)
{
printf ("Enter text:\n");
scanf("%[^\n]", c);
printf ("text:%s\n", c);
}
return 0;
}
Put a space before %[^\n] like so:
#include <stdio.h>
#include <string.h>
int main(void)
{
char command[10];
char c[10];
printf("cmd> ");
scanf( "%s", command);
if (strcmp(command, "new")==0)
{
printf ("Enter text:");
scanf(" %[^\n]", c); // note the space
printf ("text:%s", c);
}
return 0;
}
It should work now. The space makes it consume any whitespace of the previous inputs.
Here's my output when I tested it without the space:
cmd> new
Enter text:text:#
------------------
(program exited with code: 0)
And with the space:
cmd> new
Enter text:test
text:test
------------------
(program exited with code: 0)
According to the man page of scanf function, the usual skip of leading white space is suppressed if you use the [ character in the format string. So in the first case, it accepts all the characters until it meets the \n character; In the second case, after the first call of scanf function, the \n character (you press the Enter key in the first call) is still in the input buffer, so if you uses the format string "%[^\n]" in the scanf function, it reads an empty string into the buffer (As already mentioned, it skips the white space in this format case). So you can use the format string " %[^\n]" to force the scanf function to skip the white space.

Resources