I'm trying to create a program where the program guesses what kind of number the user has in mind. First it will ask the user for a minimum and maximum number, for example 1 and 10(the number I have in mind should be between 1 and 10 then).
Lets say I have the number 4 in mind and the program will output a number. I can type in L for low, H for high or G for good.
If I type in L, the program should generate a number lower than the guessed number, for H it should guess an higher number. If I input G, the program should stop and print out how many times it guessed.
I have added my code below, what am I missing?
#include <stdio.h>
#include <stdlib.h>
int main() {
int minNumber;
int maxNumber;
int counter;
printf("Give min and max: ");
scanf("%d %d", &minNumber, &maxNumber);
//printf("%d %d", minNumber, maxNumber);
int num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber;
char input[100];
do {
printf("is it %d? ", num_between_x_and_y);
scanf("%s", input);
if (input == 'L') {
counter++;
}
if (input == 'H') {
counter++;
}
} while (input != 'G');
printf("I guessed it in %d times!", counter);
return 0;
}
I do not see any "counter" variable initialization
int counter = 1;
I do not see the new random number regeneration in the cycle, it should be something like:
do {
printf("is it %d? ", num_between_x_and_y);
scanf("%s", input);
if (input[0] == 'L') {
counter++;
maxNumber = num_between_x_and_y;
}
if (input[0] == 'H') {
counter++;
minNumber = num_between_x_and_y;
}
num_between_x_and_y = (rand() % (maxNumber - minNumber)) + minNumber;
} while (input[0] != 'G');
You can't use == to compare strings (which are multiple bytes).
Either do if (input[0] == 'L') to just compare the first letter the user entered to a literal value, or if (strcmp(input,"L") == 0) to compare everything the user entered to the 1 character string literal (to use strcmp you will need to add #include <string.h>
Also your code is missing other things, like counter should be set to presumably set to zero before you use it. I assume you haven't finished your code yet because you can't get the user input part to work.
Related
I have such a program
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
float x, k;
int choose;
_Bool valid;
do {
valid = 1;
printf("\nChoose variant: \n1 - count of nums\n2 - float number\n3 - e:\nYour choose: ");
scanf(" %d", &choose);
while(isdigit(choose) == 0) {
printf("Please, choose number, not letter (number between 1 to 3): ");
fflush(stdin);
scanf(" %d", &choose);
}
while(choose > 3 || choose < 0) {
printf("Please, choose correct option (number between 1 to 3): ");
fflush(stdin);
scanf(" %d", &choose);
}
if(choose == 1 || choose == 2 || choose == 3) valid = 0;
} while (valid);
return 0;
}
I have such a program. I want to get the user to choose: 1, 2 or 3. I'm trying to put a check on characters and also on other numbers. I want the program to loop until I enter the correct one. But it does not work, I have already tried other methods to solve this problem, but it does not work for me. I have an idea that there is no cleaning here, maybe this is so?
I can also set a condition so that scanf is equal to one - this means that a character has been entered. But I want if the user enters "1gf ", for example, then the condition will also work, instead of continuing from 1.
Thank you very much in advance
Rather than checking for a numeric entry the program might scan in a character to test and then convert to an integer as in the following code snippet.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
float x, k;
int choice;
char choose;
int valid = 1;
do
{
printf("\nChoose variant: \n1 - count of nums\n2 - float number\n3 - e:\nYour choose: ");
scanf(" %c", &choose);
if((choose > '9'))
{
printf("Please, choose number, not letter (number between 1 to 3): ");
}
if((choose < '1' || (choose > '3')))
{
printf("Please, choose correct option (number between 1 to 3): ");
}
if(choose == '1' || choose == '2' || choose == '3') valid = 0;
}
while (valid);
choice = choose - '0';
printf("The choice is %d\n", choice);
return 0;
}
Following are some points to note.
The choose variable is defined as a character in lieu of an integer.
Testing is done over character ranges to determine if the entry is valid for this code.
The choice value is then determined simply by subtracting the integer value of the zero character from the entered character value.
Testing this out at the terminal resulted in the following sample output.
#Dev:~/C_Programs/Console/Choice/bin/Release$ ./Choice
Choose variant:
1 - count of nums
2 - float number
3 - e:
Your choose: e
Please, choose number, not letter (number between 1 to 3): Please, choose correct option (number between 1 to 3):
Choose variant:
1 - count of nums
2 - float number
3 - e:
Your choose: 4
Please, choose correct option (number between 1 to 3):
Choose variant:
1 - count of nums
2 - float number
3 - e:
Your choose: 2
The choice is 2
For sure, there are a multitude of ways the entries could be input and checked. This is just one way. Give it a try and see if it meets the spirit of your project.
You cant do this in standard C you need to use some additional libraries. For example in Linux ncurses.
#include <ncurses.h>
#include <string.h>
char *readstr(char *buff, size_t size, const char *allowed)
{
size_t cpos = 0;
int c;
while ((c = getch()) != ERR && c != '\n' && (cpos + 1) < size)
{
if(strchr(allowed, c)) buff[cpos++] = c;
else addstr("\b \b");
}
buff[cpos] = 0;
return c == ERR ? NULL : buff;
}
int main (void)
{
char number[7];
cbreak();
echo();
initscr();
if(readstr(number, sizeof(number), "0123456789"))
{
printf("you have entered: `%s`\n", number);
}
else
{
printf("ERROR!!!!\n");
}
return 0;
}
I'm writing a code that must identify the letter 't' or 'T' in a word, before or after the middle of it.
If the first half of the word does contain a 't' or a 'T', the program should output a 1. If the first half does not contain the letter 't' or 'T', but the second half does, then the program should output a 2. Otherwise, if there is no 't' or 'T' in the word at all, the program's output should be -1. The word entered will not have more than 50 letters.
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
t = word[i] == 't';
T = word[i] == 'T';
while(!t || !T) {
if((t || T) && i <= length / 2) {
printf("%d", '1');
} else if((t || T) && i > length / 2) {
printf("%d", '2');
//}else{
// printf("%d", '-1');
}
i++;
}
return 0;
}
If I enter any word and press enter, nothing is printed. Another thing is that when I remove the comment slashes from the two lines at the bottom, the program goes through an infinite loop.
Could someone please help?
This sounds like a school assignment, so I'll focus on advising/critiquing your code rather than giving a solution.
The first recommendation I have is to use a for loop instead of a while loop. A Rule of thumb in C is to only use a while loop when you actually don't have any idea how many things you need your program to look at.
You already have the length of the string, so set up your for loop to loop exactly once for each character.
Next you need to change how you are using printf. The %d format specifier is for printing integers, but you are passing it '1'. This is not an integer, it is the ascii representation of the symbol 1 (which is actually has the value 49, see the ascii table for more info)
You can either pass printf the value 1, or use the %c specifier, which expects ascii characters.
Better yet, just say printf("1");
That doesn't get you all the way there, but I think it lays the ground work so you can find the solution!
Condition !t || !T has no sense to be used as loop condition ...ask yourself how the loop will end ? you need just to check i is less than length
Second, the assignments t = word[i] == 't'; T = word[i] == 'T'; outside the loop have no sense ...you will be just pointing to the zero index of the string ...you should check all characters
third , the printf lines need to use %d
fourth , you appear not getting the purpose of the program printing inside loop will lead to printing many numbers and you just want to know if there is t or T you need to print single line.you may use variable int result=0; to hold the value you want and print it in the end ...of course you will need using break statement in the if((t || T) && i <= length / 2) and if((t || T) && i > length / 2) because no need for more searching
fifth, you should re-read , re-think , re-code the assignment before going bored and asking about it
sixth, there is a working version by modifying your code but you should try writing a good solution before looking at a solution as it better to solve your problems by yourself
#include <stdio.h>
#include <string.h>
int main() {
char word[50];
int i = 0, length, t = 0, T = 0;
scanf("%s", word);
length = strlen(word);
int result=0;
while( i<length) {
t = word[i] == 't';
T = word[i] == 'T';
if((t || T) && i <= length / 2) {
result=1;
break;
} else if((t || T) && i > length / 2) {
result=2;
break;
}else{
result=-1;
}
i++;
}
printf("%d",result);
return 0;
}
# include <stdio.h>
int main()
{
char name[20];
int age;
int siblings;
int childrens;
printf ("Hello my name is A.I, what is your name? \n");
scanf("%s", &name);
printf("how old are you : \n");
scanf("%d",&age);
printf("how many siblings you have: \n");
scanf("%d", &siblings);
printf("how many children you have: \n");
scanf("%d", &childrens);
printf("so your name is : %s \n", name);
printf("and your age is : %d \n", age);
printf("you have siblings : %d\n", siblings);
printf("so you have childrens : %d\n", childrens);
return 0;
}
I want to strictly limit a user's input on an integer in this program to 2-12 only. How do I do that?
#include <stdio.h>
int main(){
int i;
scanf("%d", &i);
int diceThrown, diceResult;
int sum = 0;
for(diceThrown = 1; diceThrown <= i; diceThrown++){
scanf("%d", &diceResult); //limit this input to 2-12 only, how?
sum += diceResult;
}
if(sum >= 40){
sum = sum % 40;
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
} else if(sum < 40){
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
}
return 0;
}
Also just to clarify, that I'm still a beginner in programming (like only 2 months into C.SCi course), so if you could explain it to me like I'm not a expert that would be great.
scanf has no functionality to do what you want. You can just use an if to validate input.
if(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//handle invalid input here
}
If the input is invalid it is up to you what you want to do. You could ignore the input and ask the user to enter a valid number, you can quit the whole program or just ignore the error, or something else entirely.
You can also check the input repeatedly with an while:
while(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//prompt user to enter valid input here
}
As mentioned by chux, part of handling invalid input would be to cosume the invalid input and check for EOF.
The scanf("%d", &diceResult) != 1 will assure, that scanf actually read exactly one number and no parsing errors occurred.
Consider this:
#include <stdio.h>
int main(){
int x;
do
{
printf("give a number between [2-12]\n");
scanf ("%d",&x);
}
while(x<2 || x>12);
return 0;
}
You can use a do-while loop so that you only take the values that are between the 2-12 range. That way you can force the user to give an integer as an input that is in the range that you ask for, in that case from [2,12]. Otherwise the program will turn back and request a valid input again.
I'm new in C programming language.
I need to get every digit separately that user have entered.
Here is my code:
#include <stdio.h>
int main()
{
int n[100];
printf("Enter a number: ");
scanf("%d",&n);
printf("%d %d %d",n[1],n[2],n[3]);
return 0;
} //i know that my code is not assigning like i want.
and now for example user entered a number like 123, i want the output like 1 2 3, How can i assign every digit to n[i] ? Without using string to int or int to string like atoi? Here is what Im going to do: User will enter a number and the program will search from Matrix 100x100 in row or column. i think i need to get the every digit separately to search.
No need to go to character array. The lats digit of a number n can be computed using n%10. Then you can remove the last digit using n /= 10. So this cycle would print the digits in reverse order:
void print_rev_digits(int n) {
while (n) {
printf("%d\n", n%10);
n /= 10;
}
}
And using a stack you can print the digits in the correct order. You can also use recursion for this(which will use stack for you). I am deliberately not posting a complete solution.
In this case you should read the user input character by character:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main()
{
char input[100];
int n[100];
printf("Enter a number: ");
if (fgets(input, sizeof(input), stdin)) { // attempt to read a line
int i;
for (i = 0; input[i]; i++) { // for each entered character
if (input[i] >= '0' && input[i] <= '9') { // is a digit
n[i] = input[i] - '0';
printf("%d ", input[i] - '0');
}
else if (isspace(input[i])) // end of entered integer
break;
else {
printf(stderr, "Input is not a number\n");
return -1;
}
}
printf("\n");
} else {
fprintf(stderr, "User did not enter valid input.\n");
}
return 0;
}
I'm currently learning C and am attempting to do the reverse of what some courses are asking for. miniMasterMind is an assignment I found where the user guesses numbers randomly generated by the computer. I'm attempting to make a simple flip on it, where the user tells the computer whether or not its guesses are correct for a user generated 3 digit number.
I have what I think is a fully working program, except my 3 if statements asking for user input sometimes do not work. I can't see any reason for it, but after compiling I often find one or two of the if statements to just skip over the user input. I put in system("pause")'s after each step to make it easier to see.
Each turn in the game, a different set of if statements seems to break. Why is this happening?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// Initialize variables
int UCMain = 0;
int CG1 = -1, CG2 = -1, CG3 = -1;
int win1 = -2, win2 = -3, win3 = -4;
char check1 = 'A', check2 = 'B', check3 = 'C';
int turnCount = 0;
// Print out start screen
printf("Welcome to masterMind reversed! Let's see how this works out!\n\n");
// Accept user input
printf("Type in a three digit number for the computer to guess.\n");
scanf_s("%d", &UCMain, 3);
const int UC1 = (UCMain / 100) % 10;
const int UC2 = (UCMain / 10) % 10;
const int UC3 = UCMain % 10;
printf("\nTest print, UC1: %d UC2: %d UC3: %d\n", UC1, UC2, UC3);
system("Pause");
// Start game loop
while (turnCount < 10)
{
// Random number gen
srand((int)time(0));
// 1st number
if (win1 == UC1)
{
CG1 = win1;
}
else if (win1 != UC1)
{
CG1 = rand() % 10;
}
// 2nd number
if (win2 == UC2)
{
CG2 = win2;
}
else if (win2 != UC2)
{
CG2 = rand() % 10;
if (CG2 == CG1)
{
CG2 = rand() % 10;
} // End unique check
}
//3rd number
if (win3 == UC3)
{
CG3 = win3;
}
else if (win3 != UC3)
{
CG3 = rand() % 10;
if (CG3 == CG2 || CG3 == CG1)
{
CG3 = rand() % 10;
} // End unique check
}
// End random number generation
printf("The computer guesses: %d%d%d\n", CG1, CG2, CG3);
system("Pause");
// Check if numbers are correct
if (win1 != UC1)
{
printf("Is the first number correct? Y/N\n");
scanf_s("%c", &check1, 1);
if (check1 == 'Y')
{
win1 = UC1;
} //
}// End 1st check
system("pause");
if (win2 != UC2)
{
printf("Is the second number correct? Y/N\n");
scanf_s("%c", &check2, 1);
if (check2 == 'Y')
{
win2 = UC2;
} //
}// End second check
system("pause");
if (win3 != UC3)
{
printf("Is the third number correct? Y/N\n");
scanf_s("%c", &check3, 1);
if (check3 == 'Y')
{
win3 = UC3;
} //
}// End third check
system("pause");
// Check if game is over
if (win1 == UC1 && win2 == UC2 && win3 == UC3)
{
printf("The computer wins!");
}
turnCount++;
} // End while
// Win/lose state
if (turnCount == 10)
{
printf("The computer loses!");
}
}
it is not really skipped:
it is taking a character the newline character: '\n'
Using a scanf with a space before it:
scanf(" %c", &b); // this one will work instead
Will tell the scanf that any white space characters (including the newline '\n') left on stdin should be ignored.
please read more about scanf here
scanf() is reading all user input, including line feed and carriage return characters. If the user types "1" and presses enter, you'll actually get 2 (or 3, depending on the platform) input characters, one for the digit and one or two for the newline character(s). This will stimulate 2 or 3 iterations of your loop when you only intended one.