Entering two strings using scanf function [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How can enter two strings with scanf in C?, I want to use them as follow:
#include <stdio.h>
#include <string.h>
main()
{
char kid[25];
char color[10];
scanf( "%24[^\n]", kid); // kid name
scanf( "%9[^\n]", color);
printf("%s\'s favorite color is %s.\n", kid, color);
return 0;
}

You are reading input till a \n into kid with the first scanf(). But that scanf() won't read the \n and it will remain in the input buffer.
When the next scanf() is done, the first character it sees is the \n upon which it stops reading before anything is written to color.
You could do
scanf("%24[^\n] ", kid);
scanf("%9[^\n]", color);
The space after the [^\n] will read a white-space character like \n.
If %*c is used like
scanf("%24[^\n]%*c", kid);
%*c in scanf() will cause a character to be read but it won't be assigned anywhere. * is the assignment suppressing character. See here.
But if exactly 25 characters are given as input before a \n, the %*c will just read the last character leaving the \n still in the input buffer.
If you can use a function other than scanf(), fgets() would do well.
Do
fgets(kid, sizeof(kid), stdin);
but remember that fgets() would read the \n as well into kid. You could remove it like
kid[strlen(kid)-1]='\0';
Due to this \n being read, the number characters that are read will be effectively 1 less.

Your problem is that this line does not read the \n character from the stream.
scanf( "%24[^\n]", kid); // kid name
So you read the kids name but don't remove the newline character. So the next scanf() just sees a return character on the input stream and thus you will get an empty color.
if (scanf( "%24[^\n]", kid) == 1) { // kid name
char term;
while ( scanf( "%c", &term) == 1 && term != '\n') {
/* read characters until you can't read or you reach the end of line */
}
}
else {
/* Error */
}
If the user input a kids name longer than 24 characters then you need to read and throw away these characters (or do some appropriate error handling). The end of the kids name is marked by the '\n' character.
Note: The while loop above is for illustration purposes. There are better way.
if (scanf( "%24[^\n]", kid) == 1) { // kid name
scanf("%*[^\n]"); // Note. You can not use "%*[^\n]\n". This will fail if just a newline
scanf("\n"); // So split into two lines (the first may read nothing).
}
else {
/* Error */
}

Related

How to store Math operators in variable in C and check if user entered the correct operator to perform correct operation [duplicate]

This is the basic code to a program I am writing to practise using files in C. I am trying to detect whether the output file already exists and if it does exist I want to ask the user if they would like to overwrite it or not. This is the reason that I have first opened the outfilename file in with fopen(outfilename,"r"); as opposed to fopen(outfilename,"w");.
It detects the case of the file not existing, however, if it does exist it executes the printf("Output file already exists, overwrite (y/n):"); statement but completely ignores the scanf("%c",&yn); statement!
The printf at the end of the program reads "yn=0" if the file doesn't exist and just "yn=" if it does exist. Can anybody help me?
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
int main(void) {
FILE *inf;
FILE *outf;
char filename[21],outfilename[21];
char yn='0';
printf("Please enter an input filename: ");
scanf("%s",&filename);
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
/* Open file for reading */
inf=fopen (filename,"r");
outf=fopen(outfilename,"r");
/*check that input file exists*/
if (inf!=NULL) {
/*check that the output file doesn't already exist*/
if (outf==NULL){
fclose(outf);
/*if it doesn't already exist create file by opening in "write" mode*/
outf=fopen(outfilename,"w");
} else {
/*If the file does exist, give the option to overwrite or not*/
printf("Output file already exists, overwrite (y/n):");
scanf("%c",&yn);
}
}
printf("\n yn=%c \n",yn);
return 0;
}
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
When you enter the second string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character.The string gets consumed by the scanf but the newline remains in the input buffer.
Further,
scanf("%c",&yn);
Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input.
Solution is to consume the extra newline by using:
scanf(" %c", &yn);
^^^ <------------Note the space
Or by using getchar()
You may want to check out my answer here for a detailed step by step explanation of the problem.
Use
scanf("%20s",&filename);
and remember that stdin is line buffered and on Linux is following a tty discipline
You could use GNU readline or ncurses if you want more detailed control.
scanf("%s", ...) leaves the \n terminating the line in the input. It isn't causing a problem for the next one as scanf("%s", ...) starts by skipping whites. scanf("%c", ...) doesn't and thus you read the \n.
BTW You'll probably meet other problems is you put spaces in your file name (%s doesn't read them) and if you enter too long names (%s has no input length limitations).
One solution for the problem you complained (but not the other one) is to use scanf(" %c", ...) (see the space before %c? scanf is tricky to use) which starts by skipping white spaces.
scanf("%s",&filename);
also remove the &
scanf.c:13: warning: format '%s' expects type 'char ', but argument 2 has type 'char ()[20u]'
The better way to handle this problem I found is explained here.
It recomends to use an alternative way of handle input and is very well explained.
I use always this function to get user input.
char * read_line (char * buf, size_t length) {
/**** Copyright de home.datacomm.ch/t_wolf/tw/c/getting_input.html#skip
Read at most 'length'-1 characters from the file 'f' into
'buf' and zero-terminate this character sequence. If the
line contains more characters, discard the rest.
*/
char *p;
if ((p = fgets (buf, length, stdin))) {
size_t last = strlen (buf) - 1;
if (buf[last] == '\n') {
/**** Discard the trailing newline */
buf[last] = '\0';
} else {
/**** There's no newline in the buffer, therefore there must be
more characters on that line: discard them!
*/
fscanf (stdin, "%*[^\n]");
/**** And also discard the newline... */
(void) fgetc (stdin);
} /* end if */
} /* end if */
return p;
} /* end read_line */
Old Answer
I fixed this sort of problems with this rule:
// first I get what I want.
c = getchar();
// but after any user input I clear the input buffer
// until the \n character:
while (getchar() != '\n');
// this also discard any extra (unexpected) character.
If you make this after any input, there should be not problem.

why i cant use %c instead of %s at this code [duplicate]

This is the basic code to a program I am writing to practise using files in C. I am trying to detect whether the output file already exists and if it does exist I want to ask the user if they would like to overwrite it or not. This is the reason that I have first opened the outfilename file in with fopen(outfilename,"r"); as opposed to fopen(outfilename,"w");.
It detects the case of the file not existing, however, if it does exist it executes the printf("Output file already exists, overwrite (y/n):"); statement but completely ignores the scanf("%c",&yn); statement!
The printf at the end of the program reads "yn=0" if the file doesn't exist and just "yn=" if it does exist. Can anybody help me?
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
int main(void) {
FILE *inf;
FILE *outf;
char filename[21],outfilename[21];
char yn='0';
printf("Please enter an input filename: ");
scanf("%s",&filename);
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
/* Open file for reading */
inf=fopen (filename,"r");
outf=fopen(outfilename,"r");
/*check that input file exists*/
if (inf!=NULL) {
/*check that the output file doesn't already exist*/
if (outf==NULL){
fclose(outf);
/*if it doesn't already exist create file by opening in "write" mode*/
outf=fopen(outfilename,"w");
} else {
/*If the file does exist, give the option to overwrite or not*/
printf("Output file already exists, overwrite (y/n):");
scanf("%c",&yn);
}
}
printf("\n yn=%c \n",yn);
return 0;
}
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
When you enter the second string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character.The string gets consumed by the scanf but the newline remains in the input buffer.
Further,
scanf("%c",&yn);
Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input.
Solution is to consume the extra newline by using:
scanf(" %c", &yn);
^^^ <------------Note the space
Or by using getchar()
You may want to check out my answer here for a detailed step by step explanation of the problem.
Use
scanf("%20s",&filename);
and remember that stdin is line buffered and on Linux is following a tty discipline
You could use GNU readline or ncurses if you want more detailed control.
scanf("%s", ...) leaves the \n terminating the line in the input. It isn't causing a problem for the next one as scanf("%s", ...) starts by skipping whites. scanf("%c", ...) doesn't and thus you read the \n.
BTW You'll probably meet other problems is you put spaces in your file name (%s doesn't read them) and if you enter too long names (%s has no input length limitations).
One solution for the problem you complained (but not the other one) is to use scanf(" %c", ...) (see the space before %c? scanf is tricky to use) which starts by skipping white spaces.
scanf("%s",&filename);
also remove the &
scanf.c:13: warning: format '%s' expects type 'char ', but argument 2 has type 'char ()[20u]'
The better way to handle this problem I found is explained here.
It recomends to use an alternative way of handle input and is very well explained.
I use always this function to get user input.
char * read_line (char * buf, size_t length) {
/**** Copyright de home.datacomm.ch/t_wolf/tw/c/getting_input.html#skip
Read at most 'length'-1 characters from the file 'f' into
'buf' and zero-terminate this character sequence. If the
line contains more characters, discard the rest.
*/
char *p;
if ((p = fgets (buf, length, stdin))) {
size_t last = strlen (buf) - 1;
if (buf[last] == '\n') {
/**** Discard the trailing newline */
buf[last] = '\0';
} else {
/**** There's no newline in the buffer, therefore there must be
more characters on that line: discard them!
*/
fscanf (stdin, "%*[^\n]");
/**** And also discard the newline... */
(void) fgetc (stdin);
} /* end if */
} /* end if */
return p;
} /* end read_line */
Old Answer
I fixed this sort of problems with this rule:
// first I get what I want.
c = getchar();
// but after any user input I clear the input buffer
// until the \n character:
while (getchar() != '\n');
// this also discard any extra (unexpected) character.
If you make this after any input, there should be not problem.

In this programming lined when i give the space before %c it executes perfectly but,my question why the whitespace need? [duplicate]

This is the basic code to a program I am writing to practise using files in C. I am trying to detect whether the output file already exists and if it does exist I want to ask the user if they would like to overwrite it or not. This is the reason that I have first opened the outfilename file in with fopen(outfilename,"r"); as opposed to fopen(outfilename,"w");.
It detects the case of the file not existing, however, if it does exist it executes the printf("Output file already exists, overwrite (y/n):"); statement but completely ignores the scanf("%c",&yn); statement!
The printf at the end of the program reads "yn=0" if the file doesn't exist and just "yn=" if it does exist. Can anybody help me?
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
int main(void) {
FILE *inf;
FILE *outf;
char filename[21],outfilename[21];
char yn='0';
printf("Please enter an input filename: ");
scanf("%s",&filename);
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
/* Open file for reading */
inf=fopen (filename,"r");
outf=fopen(outfilename,"r");
/*check that input file exists*/
if (inf!=NULL) {
/*check that the output file doesn't already exist*/
if (outf==NULL){
fclose(outf);
/*if it doesn't already exist create file by opening in "write" mode*/
outf=fopen(outfilename,"w");
} else {
/*If the file does exist, give the option to overwrite or not*/
printf("Output file already exists, overwrite (y/n):");
scanf("%c",&yn);
}
}
printf("\n yn=%c \n",yn);
return 0;
}
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
When you enter the second string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character.The string gets consumed by the scanf but the newline remains in the input buffer.
Further,
scanf("%c",&yn);
Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input.
Solution is to consume the extra newline by using:
scanf(" %c", &yn);
^^^ <------------Note the space
Or by using getchar()
You may want to check out my answer here for a detailed step by step explanation of the problem.
Use
scanf("%20s",&filename);
and remember that stdin is line buffered and on Linux is following a tty discipline
You could use GNU readline or ncurses if you want more detailed control.
scanf("%s", ...) leaves the \n terminating the line in the input. It isn't causing a problem for the next one as scanf("%s", ...) starts by skipping whites. scanf("%c", ...) doesn't and thus you read the \n.
BTW You'll probably meet other problems is you put spaces in your file name (%s doesn't read them) and if you enter too long names (%s has no input length limitations).
One solution for the problem you complained (but not the other one) is to use scanf(" %c", ...) (see the space before %c? scanf is tricky to use) which starts by skipping white spaces.
scanf("%s",&filename);
also remove the &
scanf.c:13: warning: format '%s' expects type 'char ', but argument 2 has type 'char ()[20u]'
The better way to handle this problem I found is explained here.
It recomends to use an alternative way of handle input and is very well explained.
I use always this function to get user input.
char * read_line (char * buf, size_t length) {
/**** Copyright de home.datacomm.ch/t_wolf/tw/c/getting_input.html#skip
Read at most 'length'-1 characters from the file 'f' into
'buf' and zero-terminate this character sequence. If the
line contains more characters, discard the rest.
*/
char *p;
if ((p = fgets (buf, length, stdin))) {
size_t last = strlen (buf) - 1;
if (buf[last] == '\n') {
/**** Discard the trailing newline */
buf[last] = '\0';
} else {
/**** There's no newline in the buffer, therefore there must be
more characters on that line: discard them!
*/
fscanf (stdin, "%*[^\n]");
/**** And also discard the newline... */
(void) fgetc (stdin);
} /* end if */
} /* end if */
return p;
} /* end read_line */
Old Answer
I fixed this sort of problems with this rule:
// first I get what I want.
c = getchar();
// but after any user input I clear the input buffer
// until the \n character:
while (getchar() != '\n');
// this also discard any extra (unexpected) character.
If you make this after any input, there should be not problem.

scanf("%*[^\n]"); usage in a c programm? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an assignment where i need to find out what scanf("%*[^\n]"); does in a c program. I know that [^\n] means that the input is read until \n and that %* puts the input in the buffer and discards it. I don't understand what usage you can get out of it, because in my understanding it just reads the input till \n and discards it then.
scanf(“%*[^\n]”); usage in a c programm?
It is somewhat common to see yet fgets() is a better approach. Recommend to not use scanf() until you know why you should not use it. Then use it in a limited way.
I don't understand what usage you can get out of it
Example usage: code attempts to read numeric text with scanf("%d", &x); but "abc\n" is in stdin so function returns 0 and data in stdin remains. scanf("%*[^\n]"); clears out (reads and discards) the "abc" in preparation for a new line of input.
int x;
int count;
do {
puts("Enter number");
count = scanf("%d", &x); // count is 0, 1 or EOF
if (count == 0) {
scanf("%*[^\n]"); // Read and discard input up, but not including, a \n
scanf("%*1[\n]"); // Read and discard one \n
}
} while (count == 0);
if (count == EOF) puts("No more input");
else puts("Success");
Variations like scanf(" %*[^\n]"); and scanf("%*[^\n]%*c"); have their own corner problems (1st consume all leading white-space, even multiple lines, 2nd fails to read anything if the next character is '\n').

Program doesn't wait for user input with scanf("%c",&yn);

This is the basic code to a program I am writing to practise using files in C. I am trying to detect whether the output file already exists and if it does exist I want to ask the user if they would like to overwrite it or not. This is the reason that I have first opened the outfilename file in with fopen(outfilename,"r"); as opposed to fopen(outfilename,"w");.
It detects the case of the file not existing, however, if it does exist it executes the printf("Output file already exists, overwrite (y/n):"); statement but completely ignores the scanf("%c",&yn); statement!
The printf at the end of the program reads "yn=0" if the file doesn't exist and just "yn=" if it does exist. Can anybody help me?
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
int main(void) {
FILE *inf;
FILE *outf;
char filename[21],outfilename[21];
char yn='0';
printf("Please enter an input filename: ");
scanf("%s",&filename);
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
/* Open file for reading */
inf=fopen (filename,"r");
outf=fopen(outfilename,"r");
/*check that input file exists*/
if (inf!=NULL) {
/*check that the output file doesn't already exist*/
if (outf==NULL){
fclose(outf);
/*if it doesn't already exist create file by opening in "write" mode*/
outf=fopen(outfilename,"w");
} else {
/*If the file does exist, give the option to overwrite or not*/
printf("Output file already exists, overwrite (y/n):");
scanf("%c",&yn);
}
}
printf("\n yn=%c \n",yn);
return 0;
}
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
When you enter the second string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character.The string gets consumed by the scanf but the newline remains in the input buffer.
Further,
scanf("%c",&yn);
Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input.
Solution is to consume the extra newline by using:
scanf(" %c", &yn);
^^^ <------------Note the space
Or by using getchar()
You may want to check out my answer here for a detailed step by step explanation of the problem.
Use
scanf("%20s",&filename);
and remember that stdin is line buffered and on Linux is following a tty discipline
You could use GNU readline or ncurses if you want more detailed control.
scanf("%s", ...) leaves the \n terminating the line in the input. It isn't causing a problem for the next one as scanf("%s", ...) starts by skipping whites. scanf("%c", ...) doesn't and thus you read the \n.
BTW You'll probably meet other problems is you put spaces in your file name (%s doesn't read them) and if you enter too long names (%s has no input length limitations).
One solution for the problem you complained (but not the other one) is to use scanf(" %c", ...) (see the space before %c? scanf is tricky to use) which starts by skipping white spaces.
scanf("%s",&filename);
also remove the &
scanf.c:13: warning: format '%s' expects type 'char ', but argument 2 has type 'char ()[20u]'
The better way to handle this problem I found is explained here.
It recomends to use an alternative way of handle input and is very well explained.
I use always this function to get user input.
char * read_line (char * buf, size_t length) {
/**** Copyright de home.datacomm.ch/t_wolf/tw/c/getting_input.html#skip
Read at most 'length'-1 characters from the file 'f' into
'buf' and zero-terminate this character sequence. If the
line contains more characters, discard the rest.
*/
char *p;
if ((p = fgets (buf, length, stdin))) {
size_t last = strlen (buf) - 1;
if (buf[last] == '\n') {
/**** Discard the trailing newline */
buf[last] = '\0';
} else {
/**** There's no newline in the buffer, therefore there must be
more characters on that line: discard them!
*/
fscanf (stdin, "%*[^\n]");
/**** And also discard the newline... */
(void) fgetc (stdin);
} /* end if */
} /* end if */
return p;
} /* end read_line */
Old Answer
I fixed this sort of problems with this rule:
// first I get what I want.
c = getchar();
// but after any user input I clear the input buffer
// until the \n character:
while (getchar() != '\n');
// this also discard any extra (unexpected) character.
If you make this after any input, there should be not problem.

Resources