I'm new to C and have been playing about and having created a basic input output program for integers (See below) I was wondering how I would go about making my program omit characters from an inputted number and then print the number without said omitted characters so for example if I wanted it to omit non-primes 1234567 entered would print 2357. Here is my current code:
#include <stdio.h>
int main() {
int number;
// printf() dislpays the formatted output
printf("Enter an integer: ");
// scanf() reads the formatted input and stores them
scanf("%d", &number);
// printf() displays the formatted output
printf("You entered: %d", number);
return 0;
}
Related
I've written a small program to practice getting user input using getchar() and outputting it using putchar() in C.
What I want my program to do:
I want the program to ask the user to enter a char, store it in a char variable, and print it out. And then I want it to ask the user to enter another char, store it in another char variable, and print it out.
The following is my code:
#include <stdio.h>
int main()
{
printf("Please enter a char: ");
char myChar = getchar();
printf("The char entered is: ");
putchar(myChar);
printf("\n");
printf("Please enter another char: ");
char myChar2 = getchar();
printf("The char entered is: ");
putchar(myChar2);
printf("\n");
return 0;
}
When I run this program in my Terminal, the following is what I see, which is not how I expect it to behave.
cnewbie#cnewbies-MacBook-Pro c % ./a.out
Please enter a char: k
The char entered is: k
Please enter another char: The char entered is:
cnewbie#cnewbies-MacBook-Pro c %
When I run the program, it outputs "Please enter a char: " and waits for me to enter a char. I type k and hit return. Then it outputs not only "The car entered is: k" but also the other lines shown above all at once.
Question: Why doesn't my program wait for me to input another char?
I'm a beginner in C and I have no clue why this is behaving this way. Please help!!
getchar also reads white space characters including the new line character '\n' that is placed in the input buffer due to pressing the Enter key.
Instead use a call of scanf the following way
char myChar;
scanf( " %c", &myChar );
^^^^
Pay attention to the leading space in the format string. It allows to skip white space characters.
I am using do...while as a loop control in C language. I need to terminate the program when the user enters "99", else the user should guess the number to terminate the program, until then the program will run. Here is the code. I don't have any compiler error, but instead it prints the number 0 to the number the users entered.
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num = 0;
do {
scanf("Enter the magic number to terminate this program: %d\n", &num);
printf("You entered : %d\n", num);
num++;
} while (num != 100);
printf("\nThe magic number is correct and the program is terminated:");
return 0;
}
Any help is appreciated.
scanf is not like Python's input, for example. It requires the exact input that you specify in the format string. In your particular case, you are expecting the users to enter "Enter the magic number to terminate this program: ", followed by a number.
One way to check this is to use the return value, which tells you the number of matched arguments:
k = scanf("...\n", &num);
printf("scanf managed to get %d inputs\n", k);
The solution is to split the input and output portions:
printf("Enter the magic number to terminate this program: ");
scanf("%d", &num);
scanf will automatically filter out whitespace between inputs, including the newlines that the user enters. You can also consume those explicitly with either "%d\n" or equivalently "%d ". However, you shouldn't do that. scanf treats any whitespace characters as "any number of whitespace", and will block until it receives the next non-whitespace character. It will also cause a problem if your stream ends without a trailing newline.
I'm a student and was given this function by our teacher to get user input. It's used for integers but I'm confused why there's a char data type. If someone could explain this function that would be great.
#pragma warning (disable: 4996)
int getNum(void)
{
char record[121] = {0};
int number = 0;
fgets(record, 121, stdin);
if( sscanf(record, "%d", &number) != 1)
{
number = -1;
}
return number;
}
When calling we do this for example:
int age = 0; //we always have to initialize
age = getNum(); //this is how we call the function to get user input
The char record[121] variable is actually an array of characters, otherwise known as a string. It is used here so that, if an erroneous input is given (instead of a valid integer input), then the input stream is still cleared by the fgets() call, which takes in all characters up to (and including) the newline character.
The sscanf function then attempts to extract a valid integer from the read character string and, if it fails, then an error value (-1) is assigned to signal that fact. If it succeeds, it assigns the given input value to number, in the same way that a successful call to scanf("%d", &number) would.
However, just using such a simple scanf() call would potentially leave 'unprocessed' characters in the input stream, which could cause problems for any subsequent input operations (or require the input stream to be cleared).
Using such a technique will also prevent undesired/unexpected effects caused by a user typing extra characters after a valid input. For example, the following (deliberately bad) code will cause a 'surprise' if you enter 1a in response to the first prompt:
#include <stdio.h>
int main()
{
int number = 0, number2 = 0;
printf("Enter first number: ");
scanf("%d", &number);
printf("Enter second number: ");
scanf("%d", &number2);
printf("Given numbers were: %d and %d.\n", number, number2);
return 0;
}
However, using the getNum() function your teacher provided, the following code is much more robust:
int main()
{
int number = 0, number2 = 0;
printf("Enter first number: ");
number = getNum();
printf("Enter second number: ");
number2 = getNum();
printf("Given numbers were: %d and %d.\n", number, number2);
return 0;
}
The program is reading lines from a file with fgets, which uses a string as storage buffer for the line. After that it processes the line to find a string that can be read as an int (%d), checks if that operation went OK, and returns the integer if so.
The function is reading input as text, storing it to the character array record. It then converts that string into an equivalent integer value using sscanf.
This is a bit safer than just using scanf directly - it ensures that if the user types non-numeric input, it's still consumed from the input stream so that it doesn't cause problems later on.
I'm trying to reference global variables in a function called "userval", and then modify those variables based on user input. Do I need to return these variables at the end of my function?
I am attempting to check my code by printing these global variables within the main function. However, I keep getting random characters.
Here is my code below.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Global Constants
#define MAX_PSWD_LEN 80
char password = 0;
int len = 0;
int upper = 0;
int lower = 0;
int digit = 0;
int special = 0;
int main(int argc, char *argv[]) {
userval();
printf(&len);
printf(&upper);
printf(&lower);
printf(&digit);
printf(&special);
}
int userval() {
printf("Please enter the minimum length of your password: \n");
scanf("%d", &len);
printf("Please enter the minimum number of uppercase letters in your password: \n");
scanf("%d", &upper);
printf("Please enter the minimum number of lowercase letters in your password: \n");
scanf("%d", &lower);
printf("Please enter the minimum number of decimal digit characters in your password: \n");
scanf("%d", &digit);
printf("Please enter the minimum number of special characters in your password: \n");
scanf("%d", &special);
printf("Thank you. \n");
return len, upper, lower, digit, special;
}
That's not how the printf function works.
The first parameter is a format string. It contains any static text you want to print along with format specifiers for any values you want to print.
For example, if you want to print only a integer followed by a newline, the format string you would use is "%d\n", where %d is the format specifier for an integer and \n is a newline character.
Any subsequent parameters are used to fill in the format. In the case of the values you want to print, you would do the following:
printf("%d\n", len);
printf("%d\n", upper);
printf("%d\n", lower);
printf("%d\n", digit);
printf("%d\n", special);
The correct way to use it would be to
printf("%p\n",(void*)&len);
But this would print the address of the variable - most likely you want to print the value of the variable. (Holds for other int` variables also in your example).
printf("%d\n",len);
While using printf the first argument is the format string and the rest of the arguments are 0 or more variables (as dictated by format string).
From standard
int printf(const char * restrict format, ...);
This is the signature of the printf function. Also regarding the format specifier ยง7.21.6.1
The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: ordinary multibyte characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments, converting them, if applicable, according to the corresponding conversion specifier, and then writing the result to the output stream.
Instead of any output stream it is stdout for printf.
#include<stdio.h>
void main(){
int num1,num2;
printf("\n Enter number 1 \t "); // Ask for input one. >>>>>>>> line 1.
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
printf("\n Enter number 2 \t "); // Ask for input Two. >>>>>>>>> line 2.
scanf("%d ",&num2);
printf("\n Entered number is %d \n",num2);
return;
}
I wish to know REASON.Please do provide it.
The code above accepts two inputs,first input is asked(By executing line 1) then user enter one number then terminal should ask to enter second input but instead it is taking other number(before executing line2 ) and then asking to enter second input(i.e after executing line 2).
In the End is is displaying the two input that are taken before executing line two but after executing line 1.
I am confused.I am interested to know reason.
I am using GCC 4.8.2 on ubuntu 14.04 64 bit machine.
Remove spaces between the scanf of access specifier.
scanf("%d ",&num1);
to
scanf("%d",&num1);
Because the scanf get the another value due to that spaces.
And kept in the buffer. After the memory has got it get assigned.
It is for all scanf function.
if I input like
Enter Number1 1
2
Entered number is 1
Enter number2 3
Entered number is 2.
It is better to use int main() and in the end write return 0;
use fflush(stdout); to flush your buffer.
After editing here is the final code
#include<stdio.h>
int main(){
int num1,num2;
printf("\n Enter number 1 \t "); // Ask for input one. >>>>>>>> line 1.
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
printf("\n Enter number 2 \t "); // Ask for input Two. >>>>>>>>> line 2.
fflush(stdout);
scanf("%d ",&num2);
printf("\n Entered number is %d \n",num2);
return 0;
}
Here is the Demo.
You need to put
fflush(stdout);
before the scanf
This will flush your buffer
(also a good idea to check the return value of scanf)
You have given a space in scanf for %d. If you remove that space after %d the program will run
Let's take this apart slowly
#include <stdio.h>
// void main(){
int main(void) {
int num1, num2;
printf("\n Enter number 1 \t ");
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
...
Use a proper function signature for main() - but that is not the main issue.
Code prints "\n Enter number 1 \t "
"%d" directs scanf() to scan for text convertible to an int in 3 steps:
A: Scan for optional leading white-space like '\n', '\t', ' '. Throw them away.
B: Scan for text representing an integer like "+1234567890". If any digits found, save the converted result to the address &num1.
C: Scanning continues in step B until a char that does not belong to the int is found. That char is "un-read" and returned to stdin.
(This is where you get in trouble as suggested by #Chandru) " " directs scanf() to scan for any number (0 or more) white spaces including '\n', '\t', ' ' and others. Then they are thrown away - not saved.
B: Scanning continues!! until a non-white-space is found. That char is "un-read" and returned to stdin.
Lastly scanf() return the value of 1 as that is how many field specifiers were converted. Code sadly did not check this value.
Recall stdin is usually line buffered, which means input is not available to user IO until Enter is hit.
User enters 1 2 3 Enter and scanf() scans the "123" and saves 123 to &num1. Then it scans "\n" as that is a white-space in step 4. and it continues waiting for more white-space.
User enters 4 5 6 Enter and the first scanf() which is not yet done, scans '4', sees it is not a white space and puts '4' back in stdin. scanf() finally returns after 2 lines are entered. At this point "456\n" are waiting in stdio for subsequent scanf().
The second scanf() then perpetuates the issue.
Recommend use fgets() only for all user input, at least until your are very skilled in C.
printf("\n Enter number 1 \t ");
char buf[100];
fgets(buf, sizeof buf, stdin);
if (sscanf(buf, "%d", &num1) != 1) Handle_BadInput();
else printf("\n Entered number is %d \n",num1);