Issue with input from users [duplicate] - c

This question already has answers here:
Which is the best way to get input from user in C?
(4 answers)
Closed 9 years ago.
I am learning C in university now. I want to get the input from the user and then print it on screen. I tried scanf and fgets and both of them crash. Please help i need to learn how to get the input and then print it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char name[256];
printf("Write something:\n");
gets(name);
printf("You wrote: %s", name) ;
return 0;
}

gets is dangerous and deprecated:
Since the user cannot specify the length of the buffer passed to
gets(), use of this function is discouraged. The length of the string
read is unlimited. It is possible to overflow this buffer in such a
way as to cause applications to fail, or possible system security
violations.
Use fgets instead:
fgets(name, 256, stdin);
or
fgets(name, sizeof(name), stdin);
and it won't crash (even if you type more than 255 chars)

Never use gets. It offers no protections against a buffer overflow vulnerability (that is, you cannot tell it how big the buffer you pass to it is, so it cannot prevent a user from entering a line larger than the buffer and clobbering memory).
gets() doesn't allow you to specify the length of the buffer to store the string in. This would allow people to keep entering data past the end of your buffer.
fgets will always read the new-line if the buffer was big enough to hold it (which lets you know when the buffer was too small and there's more of the line waiting to be read).

Related

User inputs a sentence (string). How to finish the input with Enter in C?

I've tried different types of string input(scanf, getchar, gets), but none of them can finish input with Enter. Do you guys have any ideas?
As Cheatah said, the function you looking for is fgets(). Always try to avoid gets() as it offers no protections against a buffer overflow vulnerability and can cause big problems in your program. You can read some of the answers to this question to clarify the utility of each function
Scanf() vs gets() vs fgets()
#include <stdio.h>
char str[20]; // String with 19 characters (because last character is null character)
int main() {
fgets(str, 20, stdin); // Read string
puts(str); // Print string
return 0;
}

Unable to run a piece of code to get different types of data from user in C [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
This question might look stupid but I am not used to work with C and I'm losing my mind here not knowing what is wrong.
Basically what I want is to get a number from the user, then a string, the user may write whatever he feels like, I want to keep just the first caracter of that string.
My code is the following:
#include <stdio.h>
int main()
{
int b, n;
char frase [2];
scanf("%d", &n);
fgets(frase, 2, stdin);
puts(frase);
return 0;
}
My problem is, after the fgets the program stops, no matter what I have after it, it only stops, no error messages or anything. What is happening?
What is happening?
Your code will:
For an input 123 abc:
Store 123 in n, store the space in frase followed by a null byte. Then it will print that single space and end its execution with no errors.
For an input 123 Enter abc:
Store 123 in n and store in frase the newline character \n added to the buffer when you pressed Enter, followed by a null byte, next it will print that \n and end its execution with no errors.
So it doesn't just stop, it does what it's supposed to do.
What you shoud do, to make your code more robust, is to also parse the number with fgets, and convert it with sscanf or strtol:
int n = 0;
char buffer[20];
char frase[2];
fgets(buffer, sizeof buffer, stdin);
if(sscanf(buffer, "%d", &n) != 1){
//value not parsed
}
fgets(frase, sizeof frase, stdin);
puts(frase);
Using scanf to parse inputs is rarely, if ever, a good ideia.
The fgets is grabbing the newline character that is in the buffer after scanf reads the int. Putting a getchar() before your fgets should fix the problem.

Program is not writing to the file after a whitespace is encountered in the string [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 5 years ago.
For Example if I
Input: 'stephen 8108' it outputs
'stephen'
Instead of outputing 'stephen 8108'.
Can someone help me out!
I want the full string to appear in the output.
It reads the string only till the first white space.
Even if i remove the for loop condition it doesn't seem to work it still reads only till the first white space.
#include<fcntl.h>
#include<stdio.h>
#include <unistd.h>
void main()
{
char a[100];
int i,f2,f3,f4;
f2 = creat("a.txt",0666);
f3 = open("a.txt",O_RDWR);
printf("Enter your name & Roll-no\n");
scanf("%s",a);
for(i=0;a[i] != '\0';i++);
write(f3,a,i);
close(f3);
}
This is intended sprintf functionality.
Cite: http://www.cplusplus.com/reference/cstdio/scanf/
Any number of non-whitespace characters, stopping at the first whitespace character found.
One option is to use the negated character matching (quoted from link above):
[^characters] Negated scanset
Any number of characters none of them specified as characters between the brackets.
For example, to match everything excluding a newline:
scanf("%[^\n]", a);
(Full working example below - although please don't take this as necessarily a full and perfect example of reading user input in C++...)
#include<fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
char a[100];
int fp;
fp = open("a.txt", O_CREAT|O_WRONLY|O_TRUNC);
printf("Enter your name & Roll-no\n");
scanf("%[^\n]", a);
write(fp, a, strlen(a));
close(fp);
}
However: I would really encourage you to read the extensive warnings about buffer overflows: https://stackoverflow.com/a/1248017/817132
In short, make sure you don't allow the user to write beyond your (currently 100 character long) memory allocation.
At the current state of your code, the for loop doens't have a body { ... } , so the write and the close operations would be executed only one time.
Also if you want scanf to read a string with spaces you can use %[0-9a-zA-Z ] instead of %s
Regarding the input, there are at least two problems:
The s conversion of scanf() parses until it finds whitespace, it's documented that way.
Without a field width, scanf() will continue parsing when it doesn't find whitespace, overflowing your buffer -> undefined behavior.
The quick fix is to replace scanf("%s",a); with scanf("%99[^\n]",a);. But scanf() is definitely not the best tool to read input, it is for parsing. You seem to just want to read a whole line of input and there is already a function for that: fgets(). Use it in your example like this (include string.h if you want to use this method of stripping the newline character):
fgets(a, 100, stdin);
a[strcspn(a, "\n")] = 0; // remove the newline character if it was read by fgets

C - How to read a string with only spaces using scanf [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
I'm with a little problem while doing an excercise to learn C.
The problem is: I need to read a string from the user, but if he types just a space, I need to print a space. That's okay in theory.
But, when I type the space while the program is running, it doesn't understand it as a string and it keeps waiting for me to type other things.
I'm using the scanf("%[^\n]", string_name_here);
I appreciate your help, and have a nice day! o/
And sorry for my bad english, I hope you can understand this :)
Using char *fgets(char *str, int n, FILE *stream) will make your day.
According to man :
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.
A terminating null byte ('\0') is stored after the last character in
the buffer.
Example program
#include <stdio.h>
#define MAXSTR 21
int main(void)
{
char my_str[MAXSTR] = {'\0'};
fgets(my_str, MAXSTR, stdin);
return 0;
}
Input :
Claudio Cortese
Output :
Claudio Cortese

Get words which contains space in c [duplicate]

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 7 years ago.
I need to get words from user which contains space as I expressed at title with struct statement.
For example :
#include <stdio.h>
struct knowledge
{
char name[30];
}person;
int main()
{
scanf("%s",person.name);
printf("\n\n%s",person.name);
}
When I run this program and enter a sentence like "sentence" there is no problem. It show me again "sentence".
However, when I enter "sentence aaa" it shows me just first word ("sentence"). What is the matter here? Why it doesn't show me all ("sentence aaa") I entered?
Instead of scanf() use
fgets(person.name,sizeof(person.name),stdin);
It is always a bad idea to use scanf() to read strings. The best option is to use fgets() using which you avoid buffer overflows.
PS: fgets() comes with a newline character
%s format specifier stops scanning on encountering either whitespace or end of stream. hence, you cannot input a "sentence" with space using scanf() and %s.
To scan a "whole line" with space, you need to use fgets(), instead.

Resources