Reading character input with scanf

In summary, scanf is a function in the C programming language that allows for reading character input from the user. It works by scanning the input for specified format specifiers and assigning the values to corresponding variables. This function is commonly used for user input in programs that require character-based data, such as names or numbers. However, it has some limitations and can lead to errors if not used correctly. Overall, scanf is a useful tool for reading character input in C programs, but it should be used with caution and proper understanding.
  • #1
TranscendArcu
285
0
Code:
printf("\nSpecify ascending ['a'] or descending 'd' >> ");scanf("%c",&pref);flushInputBuffer();
	extract_array(s,n,crit,array1);extract_array(s,n,2,array2);
	if (pref == '\n')pref = 'a';
	printf("\n%c\n",pref);
So the above is a snippet of code from one of the programs I am writing. My problem is that, even if I enter 'd' for my input, the program seems to decide ALWAYS that I mean to enter 'a'. I only want the computer to interpret my input as an 'a' if I just press the return key when prompted for input. Can anyone help me see the problem here?
 
Physics news on Phys.org
  • #2
It depends on what comes before.

What is the type of pref?
What is the initial value of pref?
What is the last thing you've read from input successfully?
Is there still input lying around in the input buffer (a new line perhaps)?
 
  • #3
I like Serena said:
It depends on what comes before.

What is the type of pref?
What is the initial value of pref?
What is the last thing you've read from input successfully?
Is there still input lying around in the input buffer (a new line perhaps)?

pref is type char, which matches with the %c. Pref is initially unassigned I just have
Code:
char pref;
The last successfully read character could have been almost anything, since the output of the program, a piece of which is above, has multiple functions depending on the last read character. However, there should not be any input lying around in the buffer -- the flushInputBuffer function should ensure that. In particular, I have
Code:
void flushInputBuffer()
{
	char c;
	do {
		scanf("%c",&c);
	} while (c != '\n');
}
Since I cleared the buffer at the last character scan, too, I'm not sure what the problem is.
 
  • #4
So what happens if you copy and paste these couple of lines to the beginning of your main() function?
You should see that if you type 'd' followed by Enter, that your programs reads 'd', after which the new line is flushed.

Just for fun, copy those lines a second time after the first, and see if you can type 'd' successfully again...
 
  • #5
EDIT: Let me try adding the conditional if statement. I'll let you know if it changes something.
Code:
#include <stdio.h>
void flushInputBuffer();

int main(void)
{
	char pref;
	int j;
	for (j=0;j<10;j++)
	{
		printf("\nSpecify ascending ['a'] or descending 'd' >> ");
		scanf("%c",&pref);flushInputBuffer();
		printf("\nYou entered character: %c\n",pref);
	}
	return (0);
}void flushInputBuffer()
{
	char c;
	do {
		scanf("%c",&c);
	} while (c != '\n');
}

Output:
Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> d

You entered character: d

Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> d

You entered character: d

Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> d

You entered character: d

Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> d

You entered character: d

Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> d

You entered character: d

So it seems to be working, which is why I am confused.
 
  • #6
So as it turns out, it still works with the if (pref == '\n')pref = 'a';

However, I have to press the return key twice in order to get it to tell me that I secretly entered the letter 'a'. It is not immediate.
Output:Specify ascending ['a'] or descending 'd' >> You entered character: a

Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> d

You entered character: d

Specify ascending ['a'] or descending 'd' >> a

You entered character: a

Specify ascending ['a'] or descending 'd' >> You entered character: a

Specify ascending ['a'] or descending 'd' >> You entered character: a

Specify ascending ['a'] or descending 'd' >>
 
  • #7
Here's the code again:

Code:
/*
 * test.c
 *
 *  Created on: 25. apr. 2012
 *      Author: James
 */

#include <stdio.h>
void flushInputBuffer();

int main(void)
{
	char pref;
	int j;
	for (j=0;j<10;j++)
	{
		printf("\nSpecify ascending ['a'] or descending 'd' >> ");
		scanf("%c",&pref);flushInputBuffer();
		if (pref == '\n')pref = 'a';
		printf("\nYou entered character: %c\n",pref);
	}
	return (0);
}void flushInputBuffer()
{
	char c;
	do {
		scanf("%c",&c);
	} while (c != '\n');
}
 
  • #8
So either you have old input floating around, or your program does decide to pick choice 'd', but you're mistaken in your conclusion that it picked 'a'.

You did say that your program "seemed" to always pick 'a'...

TranscendArcu said:
So as it turns out, it still works with the if (pref == '\n')pref = 'a';

However, I have to press the return key twice in order to get it to tell me that I secretly entered the letter 'a'. It is not immediate.

I do not understand what you mean.
Where and how do you need to press Enter twice?

Btw, does your extract_array() function do anything that may interfere?
 
  • #9
Oh, if you press Enter instead of a letter, your flushInputBuffer() function will force you to press Enter a second time.
 
  • #10
I like Serena said:
So either you have old input floating around, or your program does decide to pick choice 'd', but you're mistaken in your conclusion that it picked 'a'.

You did say that your program "seemed" to always pick 'a'...



I do not understand what you mean.
Where and how do you need to press Enter twice?

Btw, does your extract_array() function do anything that may interfere?

This is what the extract_array function is:
Code:
void extract_array(student_t s[], int n, int crit, aux_t array[])
{
	int j;
	char temp[STRSZ];

	for (j=0; j<n; j++) {
		switch (crit) {
			case 1: strcpy(temp, s[j].first);
				break;
			case 2: strcpy(temp, s[j].last);
				break;
			case 3: strcpy(temp, s[j].food);
		}
		strcpy(array[j].string, temp);
	}
}
I don't think this should be interfering.

I am confident that it is picking 'a' because I asked it to print out what it thought pref was after it had entered the if statement. It always returned 'a', even when I had entered 'd' as my input.
 
  • #11
Here's some sample output to show the point (just to specify, I changed the prompt output slightly, which is why it's not the same as before; the user input part is still all the same though): Choose to sort in ascending ['a'] or descending 'd' order >> d

a
Where do you want to print file?
 

1. How does scanf read character input?

scanf reads character input by using a format string as a template. It matches the characters in the input with the format specifiers in the format string, and assigns the values to the corresponding variables.

2. What is the syntax for using scanf to read character input?

The syntax for using scanf to read character input is: scanf("format string", &variable1, &variable2, ...). The format string specifies the format of the input, and the variables are the addresses where the input values will be stored.

3. How can I handle errors when using scanf to read character input?

scanf returns the number of successfully formatted and assigned input values. If this number is less than the number of variables specified, it means there was an error. You can also use the return value to check for specific errors, such as incorrect format specifiers or invalid input.

4. Can scanf read multiple characters at once?

Yes, scanf can read multiple characters at once using the %s format specifier. This will read a sequence of characters until it encounters a space or newline character. You can also specify a maximum number of characters to read by using %ns, where n is the maximum number.

5. Are there any limitations to using scanf for reading character input?

Yes, there are a few limitations to using scanf for reading character input. It does not handle input that contains spaces well, as it will stop reading at the first space. It also does not handle input that is longer than the specified variable can hold, which can lead to buffer overflow. Additionally, scanf cannot handle input that is not in the expected format, and it does not provide a way to distinguish between different types of errors.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
3
Views
887
  • Engineering and Comp Sci Homework Help
Replies
19
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
8K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
21
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Programming and Computer Science
Replies
2
Views
933
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
Back
Top