Get the whole input of a string in C - c

#include
char option[64],line[256];
main()
{
printf(">>")
(fgets(line, sizeof(line), stdin)) {
if (1 == sscanf(line, "%s", option)) {
}
}
print(option)
}
will only get the first word, for example
/>>hello world
would output
/>>hello

#include <stdio.h>
int main(){
char option[64],line[256];
printf(">>");
if(fgets(line, sizeof(line), stdin)) {
if (1 == sscanf(line, "%[^\n]%*c", option)) {//[^\n] isn't newline chars
printf("%s\n", option);
}
}
return 0;
}

In sscanf(..., "%s" ...
The scan terminates at whitespace, if you want to print entire line you just have to:
printf("%s", line)

You can use a format in scanf that allows you to match whitespaces. Look at #BLUEPIXY good anwser.
Alternatively, you can use getline(). More info here.

You can try the following code snippet :
char dump, string[40];
printf("Enter the sentece with spaces:\n");
scanf ("%[^\n]", string);
scanf("%c", &dump);
printf ("You entered: %s", string);
getchar();
getchar();

Related

2D character array in C [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
In C:
I'm trying to get char from the user with scanf and when I run it the program don't wait for the user to type anything...
This is the code:
char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c\n",ch);
Why is not working?
The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.
One way around the problem is to put a blank space before the conversion specifier in the format string:
scanf(" %c", &c);
The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.
First of all, avoid scanf(). Using it is not worth the pain.
See: Why does everyone say not to use scanf? What should I use instead?
Using a whitespace character in scanf() would ignore any number of whitespace characters left in the input stream, what if you need to read more inputs? Consider:
#include <stdio.h>
int main(void)
{
char ch1, ch2;
scanf("%c", &ch1); /* Leaves the newline in the input */
scanf(" %c", &ch2); /* The leading whitespace ensures it's the
previous newline is ignored */
printf("ch1: %c, ch2: %c\n", ch1, ch2);
/* All good so far */
char ch3;
scanf("%c", &ch3); /* Doesn't read input due to the same problem */
printf("ch3: %c\n", ch3);
return 0;
}
While the 3rd scanf() can be fixed in the same way using a leading whitespace, it's not always going to that simple as above.
Another major problem is, scanf() will not discard any input in the input stream if it doesn't match the format. For example, if you input abc for an int such as: scanf("%d", &int_var); then abc will have to read and discarded. Consider:
#include <stdio.h>
int main(void)
{
int i;
while(1) {
if (scanf("%d", &i) != 1) { /* Input "abc" */
printf("Invalid input. Try again\n");
} else {
break;
}
}
printf("Int read: %d\n", i);
return 0;
}
Another common problem is mixing scanf() and fgets(). Consider:
#include <stdio.h>
int main(void)
{
int age;
char name[256];
printf("Input your age:");
scanf("%d", &age); /* Input 10 */
printf("Input your full name [firstname lastname]");
fgets(name, sizeof name, stdin); /* Doesn't read! */
return 0;
}
The call to fgets() doesn't wait for input because the newline left by the previous scanf() call is read and fgets() terminates input reading when it encounters a newline.
There are many other similar problems associated with scanf(). That's why it's generally recommended to avoid it.
So, what's the alternative? Use fgets() function instead in the following fashion to read a single character:
#include <stdio.h>
int main(void)
{
char line[256];
char ch;
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
return 0;
}
One detail to be aware of when using fgets() will read in the newline character if there's enough room in the inut buffer. If it's not desirable then you can remove it:
char line[256];
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
line[strcpsn(line, "\n")] = 0; /* removes the trailing newline, if present */
This works for me try it out
int main(){
char c;
scanf(" %c",&c);
printf("%c",c);
return 0;
}
Here is a similiar thing that I would like to share,
while you're working on Visual Studio you could get an error like:
'scanf': function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
To prevent this, you should write it in the following format
A single character may be read as follows:
char c;
scanf_s("%c", &c, 1);
When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.
char c[4];
scanf_s("%4c", &c, _countof(c));
neither fgets nor getchar works to solve the problem.
the only workaround is keeping a space before %c while using scanf
scanf(" %c",ch); // will only work
In the follwing fgets also not work..
char line[256];
char ch;
int i;
printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
try using getchar(); instead
syntax:
void main() {
char ch;
ch = getchar();
}
Before the scanf put fflush(stdin); to clear buffer.
The only code that worked for me is:
scanf(" %c",&c);
I was having the same problem, and only with single characters. After an hour of random testing I can not report an issue yet. One would think that C would have by now a bullet-proof function to retrieve single characters from the keyboard, and not an array of possible hackarounds... Just saying...
Use string instead of char
like
char c[10];
scanf ("%s", c);
I belive it works nice.
Provides a space before %c conversion specifier so that compiler will ignore white spaces. The program may be written as below:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Enter one char");
scanf(" %c", &ch); /*Space is given before %c*/
printf("%c\n",ch);
return 0;
}
You have to use a valid variable. ch is not a valid variable for this program. Use char Aaa;
char aaa;
scanf("%c",&Aaa);
Tested and it works.

How to save a string with multiple words with scanf()

I just started programming in C and I was wondering why I can't store a string with multiple words with scanf().
For example, I enter: "That's an example" and it's stores only the first word "That's"
My code:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", &string);
printf("You entered: %s", string);
return (0);
}
You can let scanf() read more than one word with the character class conversion specifier: %[^\n] will stop at the newline and leave it pending in the input stream. Note that you must tell scanf the maximum number of characters to store into the destination array to avoid undefined behavior on long input lines. When passing an array to scanf(), you should not pass its address as &string, but just pass string as arrays decays into a pointer to their first element when passed as a function argument.
Here is a modified version:
#include <stdio.h>
int main(void) {
char string[100];
int c;
for (;;) {
printf("Please enter something: ");
/* initialize `string` in case the `scanf()` conversion fails on an empty line */
*string = '\0';
if (scanf("%99[^\n]", string) == EOF)
break;
printf("You entered: %s\n", string);
/* read the next byte (should be the newline) */
c = getchar();
if (c == EOF) /* end of file */
break;
if (c != '\n')
ungetc(c, stdin); /* not a newline: push it back */
}
return 0;
}
Note however that it is much simpler to use fgets() for this task:
#include <stdio.h>
int main(void) {
char string[100];
for (;;) {
printf("Please enter something: ");
if (!fgets(string, sizeof string, stdin))
break;
/* strip the trailing newline, if any */
string[strcspn(string, "\n")] = '\0';
printf("You entered: %s\n", string);
}
return 0;
}
#include <stdio.h>
#define BUFF_SIZE 512
int main(void) {
char string[BUFF_SIZE];
printf("Enter something: ");
fgets(string, BUFF_SIZE, stdin);
printf("You entered: %s", string);
return (0);
}
fgets() is the best option
I think there's a problem in you scanf(); I recommend you to remove & from it. then your code should see like that:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", string);
printf("You entered: %s", string);
return (0);
}
In the c language, there is no data type called a string.
A string is stored as an array of characters.
Moreover, the variable itself points to the first element of the array. Therefore, there is no need to use the '&' operator to pass the address.
So, all you have to do is the following:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", string);
printf("You entered: %s", string);
return (0);
}
Don't use '&' in scanf function.
int main()
{
char string[100];
printf("Please enter something: ");
scanf("%[^\n]%*c",string);
printf("You entered: %s", string);
return 0;
}
According to https://man7.org/linux/man-pages/man3/scanf.3.html, %s will ignore white-space characters. To capture spaces you would have to use %c with the additional size of the input argument, or use %[ format. Check if scanf will add \0 byte to the end or not.

Print the first letter of each word in a sentence

I am learning C programming and I am trying to print the first letter of each word in a sentence. I have written this code below but it doesn't seem to be working.
#include<stdio.h>
#include<string.h>
int main()
{
char s[100];int i,l;
scanf("%s",&s);
l=strlen(s);
printf("%c",s[0]);
for(i=0;i<l;i++)
{
if(s[i]==' ')
{
printf("%c",s[i+1]);
}
}
}
Input: Hello World
Expected Output: HW
Actual Output: (nothing)
The problem is in how you're reading the input:
scanf("%s",&s);
The %s format specifier to scanf reads characters until it encounters whitespace. This means it stops reading at the first space.
If you want to read a full line of text, use fgets instead:
fgets(s, sizeof(s), stdin);
just Change %s at scanf() to:
%[^\n]
This makes it scans until it finds an enter.
scanf("%[^\n]", &inisial);
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++;
j=0;
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
for(i=0;i < ctr;i++)
{
printf(" %c\n",(newString[i])[0]);
}
return 0;
}
//Here is your working code

Read a string as an input using scanf

I am new to C language and I am trying read a character and a string (a sentence; max-length 25) from a user.
Not sure what I am doing wrong in the following lines of code, its giving me an error "Segment Fault".
#include <stdio.h>
int main(){
char * str[25];
char car;
printf("Enter a character: ");
car = getchar();
printf("Enter a sentence: ");
scanf("%[^\n]s", &str);
printf("\nThe sentence is %s, and the character is %s\n", str, car);
return 0;
}
Thanks!
You have to make four changes:
Change
char * str[25];
to
char str[25];
as you want an array of 25 chars, not an array of 25 pointers to char.
Change
char car;
to
int car;
as getchar() returns an int, not a char.
Change
scanf("%[^\n]s", &str);
to
scanf( "%24[^\n]", str);
which tells scanf to
Ignore all whitespace characters, if any.
Scan a maximum of 24 characters (+1 for the Nul-terminator '\0') or until a \n and store it in str.
Change
printf("\nThe sentence is %s, and the character is %s\n", str, car);
to
printf("\nThe sentence is %s, and the character is %c\n", str, car);
as the correct format specifier for a char is %c, not %s.
str is an array of 25 pointers to char, not an array of char. So change its declaration to
char str[25];
And you cannot use scanf to read sentences--it stops reading at the first whitespace, so use fgets to read the sentence instead.
And in your last printf, you need the %c specifier to print characters, not %s.
You also need to flush the standard input, because there is a '\n' remaining in stdin, so you need to throw those characters out.
The revised program is now
#include <stdio.h>
void flush();
int main()
{
char str[25], car;
printf("Enter a character\n");
car = getchar();
flush();
printf("Enter a sentence\n");
fgets(str, 25, stdin);
printf("\nThe sentence is %s, and the character is %c\n", str, car);
return 0;
}
void flush()
{
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
}
// This is minimal change to your code to work
#include <stdio.h>
int main(){
char car,str[25];
printf("Enter a character: ");
car = getchar();
printf("Enter a sentence: ");
scanf("%s", str);
printf("\nThe sentence is %s, and the character is %c\n", str, car);
return 0;
}

how can I force scanf to take the \n character as input?

I am trying to take string input in an infinite while loop that saves the string in the same array every time, but I wish this loop to terminate when I press Enter
The code looks something like this:
int main()
{
char input[1000];
while (1)
{
scanf("%s",input);
if (input[0] == '\n'){ break; } //the problem is that scanf never gets the \n
else{...}
}
return 0;
}
A newline, \n, is considered a white-space character.
If you read the C11 spec, chapter ยง7.21.6.2 you can see, regarding the %s format specifier with scanf() family
s
Matches a sequence of non-white-space characters.
So, using a scanf() call with %s, you cannot intake a (only) \n, which is indeed a white-space charterer.
You need to use getc() to read a newline.
Alternatively, you can use fgets() which actually reads and stores the trailing newline.
FWIW, int main() should better be int main(void), at least.
The conversion "%c" matches any character including whitespace. If you really need to use scanf(), use it with that.
// you can put this in a loop
char ch;
if (scanf("%c", &ch) != 1) /* error */;
printf("the character read is '%c' and has value %d\n", ch, ch);
Note that solutions using other functions (getc(), fgets()) are way better.
Edit:
You can tell scanf() to accept specific char with scanf("%[a-zA-Z0-9 ]", ...);
Instead, use fgets() to read the line and strcspn() to lop off the potential trailing '\n'
int main(void) {
char input[1000];
while (fgets(input, sizeof input, stdin)) {
input[strcspn(input, "\n")] = '\0';
if (input[0] == '\0') {
break;
} else {
; // ...
}
}
return 0;
}
or don't lop off the '\n' #R Sahu
int main(void) {
char input[1000];
while (fgets(input, sizeof input, stdin)) {
if (input[0] == '\n') {
break;
} else {
; // ...
}
}
return 0;
}
Instead of using scanf, using fgets.
while (1)
{
if ( fgets(input, sizeof(input), stdin) == NULL )
{
// Error reading. Perhaps EOF is reached.
break; //???
}
if (input[0] == '\n'){ break; }
else{...}
}
Use fgets(input, 1000, stdin) instead.
Then use size_t s = strlen(input); and, if the returned length is adequate, look at input[s - 1] which will be the newline character, which you can test with input[s - 1] == '\n'.

Resources