read user input string with space between quotes in C - c

I have to read a user input that look like this one:
1 "string with space between quotes" 9.99
I want to store the number at the beginning of the input into an integer variable, the string between quotes into a string and the number at a double variable. I am using fgets() to get the string, but the problem is that the fgets() function keeps reading the user input until I type 0 and the number at the end of the input goes together with the string. scanf function doesn't do the job either, since it stops reading at the first space. My code looks like this:
#include <stdio.h>
int main () {
int code;
char description[50];
double value;
printf("Type in: ");
scanf("%d", &code);
fgets(description, 50, stdin);
scanf("%lf", &value);
printf("%d\n", code);
printf("%s\n", description);
printf("%2.2f", value);
}
Any ideas of how to read and store separately this 3 inputs considering they have to be at the same line?

OP's approach hopes to use fgets() to read a portion of a line, yet fgets() reads until an end-of-line '\n' is encountered.
Read the entire line with fgets() and then parse.
Using "%n" is an easy way to see if the entire string was parsed as expected.
int code;
char description[50];
double value;
#define MAX_LINE_SIZE (20 + 2 + sizeof description + 2 + 20 + 2)
char line[MAX_LINE_SIZE];
printf("Type in: ");
fflush(stdout);
fgets(line, sizeof line, stdin);
int n = 0;
sscanf(line, "%d \"%49[^\"]\"%lf %n", &code, description, &value, &n);
if (n == 0 || line[n] != '\0') {
fputs("Input formatted incorrectly\n", stderr);
return 1;
}
printf("%d\n", code);
printf("\"%s\"\n", description);
printf("%2.2f", value);
"%d \"%49[^\"]\"%lf %n" details
"%d" scan & toss whitespace, scan and save integer
" " scan and toss any whitespace
"\"" scan and match a '\"'
"%49[^\"]" scan up to 49 char that are not '\"', save in description and append '\0'
"%lf" scan & toss whitespace, scan and save double
"%n" save current offset of scan into n.

if (scanf("%d \"%49[^\"]\" %lf", &x, y, &z) == 3)
…process valid data…
else
…report erroneous input…
The relevant part for you is %49[^\"]; it matches a string until " is encountered (or it runs out of space). Note that this will not include the " into the string.

Related

Issues with scanf() and accepting user input

I am trying to take in user input with spaces and store it in an array of characters.
After, I want to take in a single character value and store it as a char.
However, when I run my code, the prompt for the character gets ignored and a space is populated instead. How can I take in an array of chars and still be allowed to prompt for a single character after?
void main()
{
char userIn[30];
char findChar;
printf("Please enter a string: ");
scanf("%[^\n]s", userIn);
printf("Please enter a character to search for: ");
scanf("%c", &findChar);
//this was put here to see why my single char wasnt working in a function I had
printf("%c", findChar);
}
scanf("%c", &findChar); reads the next character pending in the input stream. This character will be the newline entered by the user that stopped the previous conversion, so findChar will be set to the value '\n', without waiting for any user input and printf will output this newline without any other visible effect.
Modify the call as scanf(" %c", &findChar) to ignore pending white space and get the next character from the user, or more reliably write a loop to read the read and ignore of the input line.
Note also that scanf("%[^\n]s", userIn); is incorrect:
scanf() may store bytes beyond the end of userIn if the user types more than 29 bytes of input.
the s after the ] is a bug, the conversion format for character classes is not a variation of the %s conversion.
Other problems:
void is not a proper type for the return value of the main() function.
the <stdio.h> header is required for this code.
Here is a modified version:
#include <stdio.h>
int main() {
char userIn[30];
int c;
char findChar;
int i, found;
printf("Please enter a string: ");
if (scanf("%29[^\n]", userIn) != 1) {
fprintf(stderr, "Input failure\n");
return 1;
}
/* read and ignore the rest of input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("Please enter a character to search for: ");
if (scanf("%c", &findChar) != 1) {
fprintf(stderr, "Input failure\n");
return 1;
}
printf("Searching for '%c'\n", findChar);
found = 0;
for (i = 0; userIn[i] != '\0'; i++) {
if (userIn[i] == findChar) {
found++;
printf("found '%c' at offset %d\n", c, i);
}
}
if (!found) {
printf("character '%c' not found\n", c);
}
return 0;
}
scanf("%[^\n]s", userIn); is a bit weird. The s is guaranteed not to match, since that character will always be \n. Also, you should use a width modifier to avoid a buffer overflow. Use scanf("%29[^\n]", userIn); That alone will not solve the problem, since the next scanf is going to consume the newline. There are a few options. You could consume the newline in the first scanf with:
scanf("%29[^\n]%*c", userIn);
or discard all whitespace in the next call with
scanf(" %c", &findChar);
The behavior will differ on lines of input that exceed 29 characters in length or when the user attempts to assign whitespace to findChar, so which solution you use will depend on how you want to handle those situations.

Return Value of sscanf

I was reading about sscanf and i came across this:
Return Value
Each of these functions [including s_sscanf()] returns the number of fields that are successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.
I am doing error checking for my input file and i wanna make sure i get a valid line so i tried using sscanf but how do i make sure there are no more fields in the line than i expect. So if i have 3 values in a line but i only need two then that is an invalid line for me but when i use sscanf i only read in 2 variables and the rest are ignored. How do i check the entire line making sure there is no garbage in the line but im not sure what to expect so its not like i can add another variable cause the user can input anything. Someone mentioned to me that you can use * in your sscanf function but im not really sure how i haven't been able to find it anywhere where it is being implemented in code.
The scanf() family of functions returns the number of successful assignments made. If code is expecting three input items there is no way to tell from the value returned by sscanf() alone whether three or more input items were provided.
The scanf() functions operate by reading a character, attempting to match that character, making an assignment if applicable, then moving to the next character or returning from the function call. There is a conversion specifier, %n, that stores the number of characters read in this process so far (without incrementing the number of characters read). This conversion specifier can be used to determine if the input has been exhausted by the call to sscanf().
The code below provides a demonstration. Lines of input gathered by fgets() contain a newline, unless the input is too large to fit in the buffer array. Here buffer[] is large enough to store reasonably-sized inputs, but more robust code would handle oversized inputs more carefully. When sscanf() scans the input string, each character is read in turn until a failing match occurs or the end of the string is reached, so the number of read characters expected after matching "%d %d %d %n" is the same as the length of the input string, including any trailing whitespace characters.
#include <stdio.h>
#include <string.h>
#define BUF_SZ 1024
int main(void)
{
char buffer[BUF_SZ];
int x, y, z;
int pos;
printf("Enter three integers: ");
fflush(stdout);
// get user input
if (fgets(buffer, sizeof buffer, stdin) != NULL) {
// first check: does input match 3 integers?
if (sscanf(buffer, "%d %d %d %n", &x, &y, &z, &pos) != 3) {
puts("Incorrectly formatted input");
} else {
// second check: did sscanf() finish at the end of the buffer?
int expected = strlen(buffer);
if (pos != expected) {
puts("Extra input in buffer");
printf("expected = %d, pos = %d\n", expected, pos);
} else {
// everything OK
printf("You entered: %d, %d, %d\n", x, y, z);
}
}
}
return 0;
}
Sample interactions:
>$ ./a.out
Enter three integers: 1 2 3
You entered: 1, 2, 3
>$ ./a.out
Enter three integers: 1 2
Incorrectly formatted input
>$ ./a.out
Enter three integers: 1 2 3 4
Extra input in buffer
expected = 8, pos = 6
If it is desired to disallow even trailing whitespace characters, "%d %d %d%n" can be used instead. Note that in order for this to work, the newline character must be removed from buffer[] so that it is not counted as extra input. One typical way to do this is by using buffer[strcspn(buffer, "\r\n")] = '\0':
int main(void)
{
char buffer[BUF_SZ];
int x, y, z;
int pos;
printf("Enter three integers: ");
fflush(stdout);
// get user input
if (fgets(buffer, sizeof buffer, stdin) != NULL) {
// first check: does input match 3 integers?
if (sscanf(buffer, "%d %d %d%n", &x, &y, &z, &pos) != 3) {
puts("Incorrectly formatted input");
} else {
// remove trailing newline character
buffer[strcspn(buffer, "\r\n")] = '\0';
// second check: did sscanf() finish at the end of the buffer?
int expected = strlen(buffer);
if (pos != expected) {
puts("Extra input in buffer");
printf("expected = %d, pos = %d\n", expected, pos);
} else {
// everything OK
printf("You entered: %d, %d, %d\n", x, y, z);
}
}
}
return 0;
}
You may, first of all, give the conversion specifiers for the values that you are sure must be present, and then add an "assignment-allocation modifier" to capture any remaining input. I am not sure whether you are talking about sscanf, fscanf or scanf; I will just use scanf to illustrate.
The following program reads 2 integers, and places any remaining input in a string variable, the size of which is dynamically allocated:
Update: Using sscanf instead of scanf.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
int a,b;
char *s;
int n;
char src[]="1 2 This is the remainder";
n=sscanf(src,"%d %d %m[^\n]",&a,&b,&s);
if(n>2)
printf("s=%s\n", s), free(s);
return 0;
}
$ ./a.out
s=This is the remainder

Function fgets skips user input?

When I use the function fgets, the program skips the user input, effecting the rest of the program. An example program with this effect is:
#include <stdio.h>
int main() {
char firstDigit[2];
char secondDigit[2];
printf("Enter your first digit: ");
fgets(firstDigit, 1, stdin);
printf("\nEnter your second digit: ");
fgets(secondDigit, 1, stdin);
printf("\n\nYour first digit is %s and your second digit is %s.\n", firstDigit, secondDigit);
}
I then thought that maybe the problem was that fgets might be writing the newline, so I changed the code to account for that:
#include <stdio.h>
int main() {
char firstDigit[3];
char secondDigit[3];
printf("Enter your first digit: ");
fgets(firstDigit, 2, stdin);
printf("\nEnter your second digit: ");
fgets(secondDigit, 2, stdin);
printf("\n\nYour first digit is %c and your second digit is %c.\n", firstDigit[0], secondDigit[0]);
}
This time, the first input works properly, but the second input is skipped.
What am I doing incorrectly?
char firstDigit[2] and char secondDigit[2] are not large enough to hold a digit, a newline character, and a null-terminator:
char firstDigit[3];
char secondDigit[3];
Then, the calls to fgets() need to specify the size of the buffer arrays:
fgets(firstDigit, sizeof firstDigit, stdin);
/* ... */
fgets(secondDigit, sizeof secondDigit, stdin);
When instead fgets(firstDigit, 2, stdin); is used, fgets() stores at most two characters, including the \0 character, in firstDigit[]. This means that the \n character is still in the input stream, and this interferes with the second call to fgets().
In answer to OP's comment, How would you remove the unread characters from the input stream?, a good start would be to use more generous allocations for firstDigit[] and secondDigit[]. For example, char firstDigit[100], or even char firstDigit[1000] will be large enough that any expected input will be taken in by fgets(), leaving no characters behind in the input stream. To be more certain that the input stream is empty, a portable solution is to use the idiomatic loop:
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
Note here that it is necessary to check for EOF, since getchar() may return this value if the user signals end-of-file from the keyboard, or if stdin has been redirected, or in the unlikely event of an input error. But also note that this loop should only be used if there is at least a \n character still in the input stream. Before attempting to clear the input stream with this method, the input buffer should be checked for a newline; if it is present in the buffer, the input stream is empty and the loop should not be executed. In the code below, strchr() is used to check for the newline character. This function returns a null pointer if the sought-for character is not found in the input string.
#include <stdio.h>
#include <string.h> // for strchr()
int main(void)
{
char firstDigit[3]; // more generous allocations would also be good
char secondDigit[3]; // e.g., char firstDigit[1000];
printf("Enter your first digit: ");
fgets(firstDigit, sizeof firstDigit, stdin);
/* Clear input stream if not empty */
if (strchr(firstDigit, '\n') == NULL) {
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
putchar('\n');
printf("Enter your second digit: ");
fgets(secondDigit, sizeof secondDigit, stdin);
/* Clear input stream if not empty */
if (strchr(secondDigit, '\n') == NULL) {
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
puts("\n");
printf("Your first digit is %c and your second digit is %c.\n",
firstDigit[0], secondDigit[0]);
return 0;
}
It may be even better to use a single buffer[] to store lines of input, and then to store individual characters in chars. You could also write a function to clear the input stream, instead of rewriting the same loop each time it is needed:
#include <stdio.h>
#include <string.h> // for strchr()
void clear_stdin(void);
int main(void)
{
char buffer[1000];
char firstDigit;
char secondDigit;
printf("Enter your first digit: ");
fgets(buffer, sizeof buffer, stdin);
firstDigit = buffer[0];
/* Clear input stream if not empty */
if (strchr(buffer, '\n') == NULL) {
clear_stdin();
}
putchar('\n');
printf("Enter your second digit: ");
fgets(buffer, sizeof buffer, stdin);
secondDigit = buffer[0];
/* Clear input stream if not empty */
if (strchr(buffer, '\n') == NULL) {
clear_stdin();
}
puts("\n");
printf("Your first digit is %c and your second digit is %c.\n",
firstDigit, secondDigit);
return 0;
}
void clear_stdin(void)
{
int c;
while ((c = getchar()) != '\n' && c != EOF) {
continue;
}
}
For the first case, fgets(firstDigit, 1, stdin); cannot read anything from the input because the buffer has a size of only 1 byte, and fgets() must store a null terminator into the destination.
For the second case: fgets(firstDigit, 2, stdin); reads 1 byte from stdin, the digit that you typed, and cannot read the newline because the destination array is already full, allowing for the null terminator. The second fgets() reads the pending newline from the first entry and returns immediately for the same reason, not letting you type the second input.
You must allow fgets() to read at least 2 bytes by providing a buffer size of at least 3:
#include <stdio.h>
int main(void) {
char firstDigit[3];
char secondDigit[3];
printf("Enter your first digit: ");
if (!fgets(firstDigit, sizeof firstDigit, stdin))
return 1;
printf("\nEnter your second digit: ");
if (!fgets(secondDigit, sizeof secondDigit, stdin))
return 1;
printf("\n\nYour first digit is %s and your second digit is %s.\n",
firstDigit, secondDigit);
return 0;
}
Note that if you type more than a single character before the enter key, the program will still behave in an unexpected way.
This is a buffer problem. When you press enter, don't know why it is saved in the stdin buffer.
After you perform an fgets(...) you must type fflush(stdin); on all circumstances.
Something like this:
printf("Enter your first digit: ");
fgets(firstDigit, 1, stdin);
fflush(stdin);

fgets() doesn't work as expected in C

Given the following code:
#include <stdio.h>
int main()
{
int testcase;
char arr[30];
int f,F,m;
scanf("%d",&testcase);
while(testcase--)
{
printf("Enter the string\n");
fgets(arr,20,stdin);
printf("Enter a character\n");
F=getchar();
while((f=getchar())!=EOF && f!='\n')
;
putchar(F);
printf("\n");
printf("Enter a number\n");
scanf("%d",&m);
}
return 0;
}
I want a user to enter a string, a character and a number until the testcase becomes zero.
My doubts / questions:
1.User is unable to enter a string. It seems fgets is not working. Why?
2.If i use scanf instead of fgets,then getchar is not working properly, i.e whatever character I input in it just putchar as a new line. Why?
Thanks for the help.
Mixing functions like fgets(), scanf(), and getchar() is error-prone. The scanf() function usually leaves a \n character behind in the input stream, while fgets() usually does not, meaning that the next call to an I/O function may or may not need to cope with what the previous call has left in the input stream.
A better solution is to use one style of I/O function for all user input. fgets() used in conjunction with sscanf() works well for this. Return values from functions should be checked, and fgets() returns a null pointer in the event of an error; sscanf() returns the number of successful assignments made, which can be used to validate that input is as expected.
Here is a modified version of the posted code. fgets() stores input in a generously allocated buffer; note that this function stores input up to and including the \n character if there is enough room. If the input string is not expected to contain spaces, sscanf() can be used to extract the string, leaving no need to worry about the newline character; similarly, using sscanf() to extract character or numeric input relieves code of the burden of further handling of the \n.
#include <stdio.h>
int main(void)
{
int testcase;
char arr[30];
char F;
int m;
char buffer[1000];
do {
puts("Enter number of test cases:");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
/* handle error */
}
} while (sscanf(buffer, "%d", &testcase) != 1 || testcase < 0);
while(testcase--)
{
puts("Enter the string");
/* if string should not contain spaces... */
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
/* handle error */
}
sscanf(buffer, "%29s", arr);
printf("You entered: %s\n", arr);
putchar('\n');
puts("Enter a character");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
/* handle error */
}
sscanf(buffer, "%c", &F);
printf("You entered: %c\n", F);
putchar('\n');
do {
puts("Enter a number");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
/* handle error */
}
} while (sscanf(buffer, "%d", &m) != 1);
printf("You entered: %d\n", m);
putchar('\n');
}
return 0;
}
On the other hand, if the input string may contain spaces, fgets() can read input directly into arr, but then the stored string will contain a \n character, which should probably be removed. One way of doing this is to use the strcspn() function to find the index of the \n:
#include <string.h> // for strcspn()
/* ... */
puts("Enter the string");
/* or, if string may contain spaces */
if (fgets(arr, sizeof arr, stdin) == NULL) {
/* handle error */
}
/* replace newline */
arr[strcspn(arr, "\r\n")] = '\0';
printf("You entered: %s\n", arr);
putchar('\n');
/* ... */
Note that a maximum width should always be specified when using %s with the scanf() functions to avoid buffer overflow. Here, it is %29s when reading into arr, since arr can hold 30 chars, and space must be reserved for the null terminator (\0). Return values from sscanf() are checked to see if user input is invalid, in which case the input is asked for again. If the number of test cases is less than 0, input must be entered again.
Finally got the solution how can we use scanf and fgets together safely.
#include <stdio.h>
int main()
{
int testcase,f,F,m;
char arr[30];
scanf("%d",&testcase);
while((f=getchar())!=EOF && f!='\n')
;
while(testcase--)
{
printf("Enter the string\n");
fgets(arr,30,stdin);
printf("Enter a character\n");
F=getchar();
while((f=getchar())!=EOF && f!='\n')
;
putchar(F);
printf("\n");
printf("Enter a number\n");
scanf("%d",&m);
while((f=getchar())!=EOF && f!='\n')
;
}
}
We need to make sure that before fgets read anything,flushout the buffer with simple while loop.
Thanks to all for the help.
A simple hack is to write a function to interpret the newline character. Call clear() after each scanf's
void clear (void){
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
Refer to this question for further explaination: C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf

Why is strtok printing only first word?

I am using strtok for converting string into individual words. I have done the following:
int main() {
char target[100];
char *t;
scanf("%s",target);
t = strtok(target," ");
while (t!= NULL)
{
printf("<<%s>>\n", t);
t = strtok (NULL, " ");
}
return 0;
}
The input is a string such as 'this is a string', the output I am getting is<<this>>.
The way you have written scanf it will accept string till white space only
scanf("%s",target);
SO You need to change the way you take input from console
scanf("%99[^\n]",target);
Change:
scanf("%s",target);
to:
fgets(target, 100, stdin);
since the first won't stop when encounters the whitespace in your input.
Output:
this is a string
<<this>>
<<is>>
<<a>>
<<string
>>
Notice how the newline fgets() stores affects the output. You can simply discard it if you want, like this:
fgets(target, 100, stdin);
target[strlen(target) - 1] = '\0';
and now the output is:
this is a string
<<this>>
<<is>>
<<a>>
<<string>>
If you want to continue using scanf(), then you can use the below code snippet:
#include<stdio.h>
#include <string.h>
int main() {
char target[100];
char *t;
//scanf("%s",target);
scanf("%99[0-9a-zA-Z ]", target);
printf("%s\n",target);
t = strtok(target," ");
while (t!= NULL)
{
printf("<<%s>>\n", t);
t = strtok (NULL, " ");
}
return 0;
}
Working code here.
Just writing scanf("%s",target); will read the input only till the first white space; which is why you get only the first word as the output. By writing scanf("%99[0-9a-zA-Z ]", target);, you are reading 99 characters (including numbers 0-9, a-z or A-Z and white space) from the input stream.
Hope this is helpful.

Resources