Restrict input to symbols and other numbers (с program) - c

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;
}

Related

scanf() adds character to string

I have this code and it keeps adding what ever the guesses string is to the wordle string when I compare them, resulting in them to never be the same. How can I fix this?
#include <string.h>
int main() {
char wordle[5];
char guesses[5];
int guess = 5;
int value;
printf("Please input a secret 5 letter word:\n");
scanf("%s",wordle);
while (guess != 0){
printf("You have %d tries, please guess the word\n",guess);
scanf("%s",guesses);
value = strcmp(wordle,guesses);
if (value == 0){
printf("you win\n");
break;
}
guess = guess - 1;
}
return 0;
}```
Your program has undefined behavior. You're making two mistakes.
If your user enters 5 characters, it takes 6 characters to store the string. The program would attempt to write a null terminator into wordle[5] which is not a valid index.
Your user could enter any number of letters. You need to make sure they don't overflow your buffer.
#include <stdio.h>
#include <string.h>
int main() {
char wordle[6];
char guesses[6];
int guess = 5;
int value;
int chars_read;
do {
printf("Please input a secret 5 letter word:\n");
chars_read = scanf("%5s%*s\n", wordle);
} while(chars_read != 1 && strlen(wordle) != 5);
while (guess != 0){
do {
printf("You have %d tries, please guess the word\n", guess);
chars_read = scanf("%5s%*s\n", guesses);
} while(chars_read != 1 && strlen(wordle) != 5);
value = strcmp(wordle, guesses);
if (value == 0){
printf("you win\n");
break;
}
guess = guess - 1;
}
return 0;
}
See it in action
scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
MSC24-C. Do not use deprecated or obsolescent functions
Your strings for wordle and guesses are too short. You need to make room for '\0'. They should be 6 bytes long not 5.
char wordle[6];
char guesses[6];

Number guessing what the user has in mind C

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.

Using Array Integer

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;
}

Check if input is a string (4 characters only) and if not return to input again

My aim is to accept 4-digit numbers, and 4-character strings (string should not contain digits or special characters)
If an invalid input is given the program should not terminate and it must allow the user to enter the details and continue until he wish to terminate.
I am able to find whether the input is a digit.
if(scanf("%d",&input)!=1)
{
printf("enter the number please");
... // I have option to re enter using while and flags
}
else
{
// I continue my work
...
}
To check it is four digits I have tried using the commands
i=0;
num = input;
while(num>0)
{
i = i+1;
num = num/10;
}
if(i==4){
...//I continue
}
else
printf("please enter four digit");
I have no idea of checking the same for characters. (I know how to check its length using strlen())
Please help me with the code in C. (Also help me to reduce/optimize the above logic to check whether the input is a 4-digit number)
I believe you want 2 inputs a number and a string. You can do that as
int number= 0;
char string[10] = { 0 };
do {
printf("please enter four digit");
scanf("%d", &number);
if(number >=1000 && number<= 9999)
break;
} while(1);
do {
printf("please enter four character string");
fgets(string, sizeof(string), stdin);
if(strlen(string) == 4)
break;
} while(1);
To check it is four digit number you can simply put a check whether the number lies between 1000 and 9999. (I am assuming you don't want the number to start with 0.)
strtol can help:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char s[32], *p;
int x;
fgets(s, sizeof(s), stdin);
if ((p = strchr(s, '\n')) != NULL)
*p = '\0';
x = (int)strtol(s, &p, 10);
if ((p - s) == 4) {
printf("%d\n", x);
} else {
printf("Please enter four digit\n");
}
return 0;
}
char input[16];
int ok = 1, k = 0;
if (scanf("%s", input) > 0 && strlen(input) == 4) {
// check if it's a word
for (; k < 4; k++)
if (!isalpha(input[k])) {
// check if it's a number
for (int k = 0; k < 4; k++)
if (!isdigit(input[k]))
ok = 0;
break;
}
}
else ok = 0;
if (!ok)
printf("invalid input, please enter a 4-digit number or 4-letter word");
else {
printf("valid input");
...
}
You can use gets()1 fgets() to get the whole line and check line length. If the first character is between '0' and '9' then check the remaining if they are 3 numbers too. If the first character is a valid character in string then check the 3 remaining chars if it's also valid in string.
1See Why is the gets function so dangerous that it should not be used?

scanf resulting in infinite loop [duplicate]

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 9 years ago.
I had this problem before but went around it using other operator. But the same operator can't be used here I think (the getche();). Anyway this works well and good but if I input a letter it goes into an infinite loop.
printf("Enter the number of the passenger you wish to edit.");
scanf("%d", &userchoice);
do
{
if(userchoice <= count || userchoice <= 1)
{
flag = 0;
}
else
{
printf("Please enter a valid input!");
scanf("%d", &userchoice);
flag = 1;
}
} while (flag == 1);
You should see this answer :
https://stackoverflow.com/a/1716066/2263879
The problem is with your scanf.
Yes , it will go into .
Since you are checking for userchoice<=1 , letter ascii value would be compared which will always be false and flag will always be 1
P.S: I am assuming count is pretty small number here , since you have not provided the value of it.
Do you mean userchoice between 1 and count, then the first if is incorrect.
This code works, when you want to test in-between 1 and count.
#include <stdio.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
signed int count = 5;
signed int flag = 1;
signed int userchoice = 0;
printf("Enter the number of the passenger you wish to edit:");
scanf("%d", &userchoice);
do {
if(userchoice <= count && userchoice >= 1) {
flag = 0;
} else {
char c = '0';
if (scanf("%d", &userchoice) == 0) {
printf("Please enter a valid input!\n");
do {
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
}
}
} while (flag == 1);
printf("Done!");
}
Output:
a is not valid, because it is not a digit, 6 is bigger than count. 3 is possible and gets accepted.
Enter the number of the passenger you wish to edit:a
Please enter a valid input!
6
3
Done!

Resources