C-code only: Ask user if they are married or not. User must input 0 for false. User must input any other character for true. Do it using only one printf.
Ok, so I always turn to stackoverflow as a last resort, because I am trying to figure it out. This, is what I came up with but I get errors and I have done other things like take out scanf("%f", &t), because that is essentially unnecessary. I also made char married[3]; char married[] ="; instead but that doesn't work.
Here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char married[3];
unsigned long t;
int f;
scanf("%f", &t);
scanf("%d", &f);
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married? %s", married);
if (f == 0)
{
married == "no";
}
else
married == "yes";
return 0;
}
Thanks the help is appreciated. Please go easy on me just learning...
I'm not sure you are interpreting the question correctly. It says to print whether the person is married or not. So that's the expected output. It suggests you can do that with one printf. It does not mean the whole program only has one printf so you are allowed to have another printf for the user prompt. It just means avoid using two printfs for the output (one for YES and another for NO). One way to do this is to use the ? operator.
For example:
#include <stdio.h>
#include <string.h>
int main(void)
{
int married = 1;
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?");
scanf("%d", &married);
printf("You %s married\n", married ? "ARE" : "ARE NOT");
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char married[4]; //Space for 'yes' + the NUL-terminator
//unsigned long t; Why do you have this?
int f = 1; //Initialize variables
//scanf("%f", &t); ??
//scanf("%d", &f); Wrong place
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?"); //Remove %s and the argument. You are trying to print an uninitialized array
scanf("%d", &f); //scan input after printing
if (f == 0)
strcpy(married, "no");
else
strcpy(married, "yes"); //Copy strings using strcpy function
return 0;
}
Related
Pls check it out and help meeee I'm stuck at it since 2+ hours (the "score" variable and other variables that you might see aren't mentioned here because my original code is too long, so I've just listed the important parts of it):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
while (1) { //using 1 as a condition since "true" doesn't work
char* low(char* question) { // a function used for converting the user input into all lowercased
for (int i = 0; question[i]; i++) {
question[i] = tolower(question[i]);
}
}
printf("1. Is Python a programming language or a creature? ");
char question[25];
scanf("%s", &question);
low(question);
if (strcmp(question, "programming language") == 0 || (strcmp(question, "creature") == 0)) {
printf("Correct! It's both actually 1+ ");
score += 1;
break;
} else {
printf("Invalid Input ");
continue;
}
}
}
Problem: It keeps printing out Invalid input even if the answer is correct
Instead of this:
scanf("%s", &question);
This:
scanf("%s", question);
Reason: question is an array, so when it gets passed as a function parameter, it becomes a pointer to the first element in the array - which is where scanf needs to write to.
It's just a code to receive user inputs in C program, but fails to do so and accepts null space as input. I have tried fgets() as well and the same thing keeps happening. Please advice on how to fix.
#include <math.h>
#include <stdio.h>
//#include <string.h>
#define len 16
int main(void)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,i=0,j=0;
printf("enter the number of cards:");
n = getchar();
//scanf("%d",&n);
int c1[len][n],card[len][n];
char buf[len];
printf("Enter card number:");
gets(buf);
system("Pause");
return (0);
}
"...code to receive user inputs in c program, but fails to do so and accepts null space as input..."
The reasons your existing code has problems is covered well in the comments under your post.
Consider a different approach: Define the following:
char inBuf[80] = {0};//
int numCards = 0;//Pick variable names that are descriptive (n is not)
int cardNum = 0;
bool isnum;
Then use it in conjunction with printf() etc.
printf("enter the number of cards:");
if(fgets(inBuf, sizeof(inBuf), stdin))//will read more than just a single char, eg. "12345"
{
int len = strlen(inBuf);
isnum = true;
for(int i=0;i<len;i++)
{
if(!isdigit(inBuf[i]))
{
isnum = false;
break;
}
}
if(isnum)
{
numCards = atoi(inBuf);
}
else
{
printf("input is not a number\n"
}
}
printf("Enter card number:");
if(fgets(inBuf, sizeof(inBuf), stdin))
{
...
Repeat variations of these lines as needed to read input from stdin, with modifications to accommodate assignment statements based on user input i.e. an integer (this example is covered), a floating point number, a string (eg. a persons name)
Although there is more that you can do to improve this, it is conceptually viable for your stated purpose...
I have run into a problem I don't really know how to fix. I mostly code in Python, and this is my first program in C.
#include <stdio.h>
int ask(void) {
scanf("Var");
return 0;
}
int count(ask) {
scanf("number1");
return 0;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number");
ask();
count(ask());
printf("Thanks!");
printf(%count%);
return 0;
}
However, I keep getting an error.
main.c:22:10: error: expected expression
printf(%count%);
^
main.c:22:17: error: expected expression
printf(%count%);
^
2 errors generated.
compiler exit status 1
What I want it to do is, the user types a number, and then it prints out that number. It's not complete though. I want it to write numbers 1 - the users input, and when it gets the number right, it prints "Your number is:" (number)
The problem (as already pointed out) is that you aren't actually getting and storing the value from the scanf() call. Additionally, printf(%count%) is not valid C syntax. You need to use printf("%d", count).
Putting all that together:
#include <stdio.h>
int ask(void) {
int input_number;
scanf("%d", &input_number);
getchar(); # This is so that the '\n' in is read when you hit Enter
return input_number;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number");
int input_number = ask();
printf("Thanks!");
printf("The number you entered is %d\n", input_number);
return 0;
}
Some things to read to avoid making mistakes like these:
printf tutorial: https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm
scanf tutorial: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
You are using incorrect format for printing.
you are using this code printf(%count%); instead you should use this code printf("%d",count(variablename));
Here is the code that you can use:
#include <stdio.h>
int ask(void) {
//scanf("Var");
int var; //declaring integer type varible in C
scanf("%d",&var); //taking input
return var; //returning what is being input by user
}
//int count(ask) //its function you are passing
//so it should have parenthesis
int count( int a )
{
return a;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number: ");
//ask();
count(ask()); // when you will call it will automatically run ask as well
// and it will pass int value that user will input
printf("Thanks!");
int var1=ask(); // this varible var1 will store value returned by ask()
printf("%d",count(var1) ); //this will print that value
//I dont know what you wanted to do here
//maybe you wanted to print value returned by count function
//so it can be done by this
return 0;
}
printf format: printf("%formatspecifier",variable name); Format specifiers are %d for a integer. %f for a floating value. %c for a charcater. s for a string and so on.
In C, we use % to specify output/input type. %d for integer, %f for float, %c for character, %s for string and thats your basic knowledge.
for printf:
printf("%d", varname);
for scanf:
scanf("%d", &varname);
'&' means location in memory.
Your program got many syntax errors, here is some code:
#include<stdio.h>
int ask(){
int varin;
scanf("%d", &varin);
return (varin);
}
int count(int countin){
return (countin); //just an example code, or whatever you wanna do here.
}
int main(){
int out;
printf("Whatever\n");
out = ask();
count(out);
printf("%d", out);
return 0;
}
I know this question gets asked a hundred times over, and I've scoured all of the possibilities, but I guess I'm not adept enough to know where this problem lies. I'm programming a program where I need to fill a struct with data (ints and strings). The first time I tried it it skipped over everything but the first one, but I didn't panic since I remembered from class I needed to use fflush(stdin) to overcome this. Websites I've searched vote against use of fflush(stdin), since it has undefined behaviour. They say using getchar() would eat the extra newline, thus fixing the problem. Hence my code:
int manNode(){
Item *p;
int helper;
p = (Item*)malloc(sizeof(Item));
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
scanf("%u",&helper); //selecting an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
getchar(); //I've just put getchars everywhere for safety.
p->entrytype = helper-1;
helper = 0;
printf("Vul een naam in:\n");
scanf("%s", p->name); //this one fills in fine
getchar();
printf("Vul een vaknaam in: \n");
scanf("%s", p->course); //this one gets skipped if I type more than one letter in the last scanf()
getchar();
printf("Vul een starttijd in:\n"); //From here on out everything gets skipped
p->start = getTijd();
checkTijd(p->start);
printf("Vul een eindtijd in: \n");
p->end = getTijd();
checkTijd(p->end);
I know it's a bit messy, but focus on the scanfs and getchars. getTijd() also has a couple of scanfs in it that scan for integers, they also get skipped. I don't know where to go from here. (The code isn't incomplete, the rest is just irrelevant)
you can define a new getchar
#include <stdlib.h>
#include <stdio.h>
#define getchar(x) (scanf("%c", x))
int main ()
{
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
return 0;
}
update: this may be a better approach
#include <stdlib.h>
#include <stdio.h>
void work_to_do()
{
#define getchar(x) (scanf("%c", x))
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
#undef getchar
}
int main ()
{
work_to_do();
return 0;
}
to solve the scanf newline ignorance and getchar (but still scanf ignores whitespace)
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#define __getchar() (read(2, NULL, 1)) // 2 stands for standard error, we can make the user enter a character.
void work_to_do()
{
char y[10];
__getchar();
scanf("%s", y);
printf("got %s\n", y);
__getchar();
}
int main ()
{
work_to_do();
return 0;
}
and it's good to take a look at this:
Read space-separated values from file
scanf works as documented. Also, there is nothing wrong with scanf so long as its function is understood.
I created a copy of your code and distilled it to highlight what you want to do. You will need to fill-in the rest yourself.
In this code you need to enter a digit and press enter. Then enter a string and press enter, etc. Note. the fflush(stdout) statement is part of the standard C implementation per K&R. The fflush forces the contents of the buffer out to the console. This flushing makes for a reasonable user/computer dialog.
#include <stdio.h>
main()
{
char string[100];
int helper;
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
fflush(stdout);
scanf("%d",&helper); //select an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
printf("Vul een naam in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een vaknaam in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een starttijd in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een eindtijd in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
}
This code ran on Eclipse with a Microsoft C Compiler.
Also, let me emphasize that if you enter: 1 AAA BBB CCC DDD and press enter then scanf will get executed five times. In this example, the code would run to completion!
So you need to trace your code logic (in this case a straight line) to see how the scanfs are invoked based on what data is entered.
Hope this helps. Please ask if more questions.
When I run the program and answer "yes", it tells me that I am wrong. Does anybody know a way to execute this type of program?
#include <string.h>
#include <stdio.h>
int strcmp(const char *str1,const char *str2 );
// I am trying to make a program that asks the user to input an answer
int main()
{
char answer[20];
printf("Can birds fly?\n");
scanf("%s", &answer[20]);
if(strcmp(answer, "yes") == 0)
{
printf("You are right");
}else
{
printf("You are worng");
}
return 0;
}
Change this line:
scanf("%s", &answer[20]);
to:
scanf("%s", answer);
You have to pass to scanf the address where you want to put the string, with answer[20] you pick the value of the 21th character in the string (undefined because the string is 20 characters only) and then take a pointer to it (garbage, you may even get an access violation).