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

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

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;
}

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

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.

Unwanted line break in C [duplicate]

This question already has answers here:
Removing trailing newline character from fgets() input
(14 answers)
Closed 3 years ago.
I have created a little script in C which displays text in a Linux console, but I found one problem - the script adds a line break at the end of text. I have no idea why, normally I should get line break after /n.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char buf[1024];
char txt[100];
printf("Insert a text: ");
fgets(txt, 100, stdin);
snprintf(buf, sizeof(buf), "echo '%s'", txt);
system(buf);
}
The structure of the code has to stay the same. I need to use system function and snprintf().
I want to make a few things clear. Right when I'm running this script the output looks like this:
root#test:/home# ./app
Insert a text: Hello
Hello
root#test:/home#
How can I remove this newline after Hello?
fgets consumes the \n character in the buffer which you press after entering data. Just add
txt[strcspn(txt,"\n")] = 0;
just after the fgets to replace the \n character at the end of txt with a NUL-terminator. The strcspn function, in your case, counts the number of characters in txt until a \n character. If no newline character is found, then it returns the length of txt(strlen(txt)).
BTW, you need to include string.h if you want to use this function:
#include <string.h>
The problem you're facing is related with how fgets() behave. As per the man page
char *fgets(char *s, int size, FILE *stream);
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.
So, it reads and stores the trailing \n (newline) generated by pressing ENTER after the input into txt. If you don't want that \n to be present in txt, you need to remove that from the input buffer manually before printing the contents of txt.
You can use strchr() or strcspn() to find out the possible \n and replace that with \0 (null) to solve your issue.

Issue with input from users [duplicate]

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).

Resources