c - how to break scanf with no enter and no string [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project for school and in it, I need to get a four digit number and then continue immediately with no enter. For example: "Enter a number: 1424" and then it just continues, and you can't enter anymore numbers, aw well as Enter key pressing should not be needed.
I tried scanf("%4d",&num); but it waits for Enter key.
And one more restriction is... I can't use strings in this project, so all the solutions must be without strings.

The only way to organize input without Enter key press are functions getch and getche from conio.h header, that I suppose is not in C/C++ standard. So POSIX standard names are _getch and _getche.
With that functions you will read character - which are not strings if you process each char separately.
UPDATE:
My solution is:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch; // to store an input - single char
int number = 0; // to make number from inputs
printf("Enter a number: ");
int digits_cnt = 0;
while (digits_cnt < 4)
{
ch = _getche();
if (isdigit(ch))
{
number *= 10; // add an order to number
number += ch - '0'; // add a decimal digit to number
digits_cnt++; // count this digit to stop loop
}
}
// just to check result
printf("\nThe number %d was entered.\n", number);
return 0;
}
I assume that all 4 digits should become a number, but, perhaps, you need to do something else with them.

For reading 4 digits you probably want use char * fgets ( char * str, int num, FILE * stream ); that will do exactly what you are asking for. You should not use scanf for interactive input you can find why in this article
To the string part since you are typing input in ascii you are already working with strings(arrays of chars).

Related

Is this program actually valid [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include<stdio.h>
int main()
{
char word[1000];
scanf("word%s", word);
printf("%s", word);
}
It seems that when I input any string, as long as I type out "word" first, I get proper output.
But is this program actually valid
It compiles and therefore is valid from a syntax perspective. It's also fine in order to check that a prefix is used.
However, there are at least two ways to get undefined behaviour:
scanf might store more than 1000 characters (read 999 and one for the final \0)
scanf might read none if the input does not start with "word"
You should therefore check the result of scanf, initialize word, and also limit the maximum number of characters that scanf reads:
#include<stdio.h>
int main()
{
char word[1000] = {0};
int ret = scanf("word%999s", word);
if ( ret == 1 ) {
printf("%s", word);
}
}
this program is valid ,but you have to be careful about buffer overflow , which means if user input more than 999 chars this will lead to undefined behavior , so I suggest this:
scanf("word%999s", word);
also as you said as long as I type out "word" first ,otherwise char word[1000] will be uninitialized.

Printing leading zeros in a number in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm working on a project and I want my program to read a strictly 5 digits number with a leading zero.
How can I print the number with the leading zero included?
Plus: how can I provide that my program reads 5 digits including a zero as a leading number?
I assume you want to read in int variable. If so you can try the below solution.
#include<stdio.h>
void main()
{
int a;
scanf("%5d", &a);
printf("%05d",a);
}
The best way to have input under control is to read in a string and then parse/analyze the string as desired. If, for example, "exactly five digits" means: "exactly 5 digits (not less, not more), no other leading characters other than '0', and no negative numbers", then you could use function strtol, which tells you where number parsing has ended. Therefrom, you can derive how many digits the input actually has:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[50];
if (fgets(line,50,stdin)) {
if (isdigit((unsigned char)line[0])) {
char* endptr = line;
long number = strtol(line, &endptr, 10);
int nrOfDigitsRead = (int)(endptr - line);
if (nrOfDigitsRead != 5) {
printf ("invalid number of digits, i.e. %d digits (but should be 5).\n", nrOfDigitsRead);
} else {
printf("number: %05lu\n", number);
}
}
else {
printf ("input does not start with a digit.\n");
}
}
}
use printf family with '%05d" to print number with leading zeros. use sscanf to read this value (leading zeros are ignored).
Consult the following code:
int a = 25;
int b;
char buffer[6];
sprintf( buffer, "%05d", a );
printf( "buffer is <%s>\n", buffer );
sscanf( buffer, "%d", &b );
printf( "b is %d\n", b );
output is:
buffer is <00025>
b is 25

How to read n numbers separated by space in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to read n integers from user during execution and the numbers are separated by spaces. It would be the best to be received as an array. For input 1 22 3 445 3, the result is, array[0]=1, array[1]=22 and so on. I have to do it in C. Can't use
scanf("%d %d %d", &var1, &var2, &var3);
because, I don't know how many such numbers would be inserted. The value of n would be read from user just before reading this data.
enum { MAX_NUMBERS = 1000000 }; // Choose appropriate upper bound
int n;
if (scanf("%d", &n) == 1 && n > 0 && n < MAX_NUMBERS)
{
int array[n];
for (int i = 0; i < n; i++)
{
if (scanf("%d", &array[i]) != 1)
…process error — terminate loop?…
}
…use array…
}
You can read multiple numbers with scanf() using a loop as shown. You've no idea whether they were all presented on a single line, or each was on its own line, or whether there were many blank lines between successive numbers (or any permutation of all these possibilities).
The scanf() family of functions basically do not care about newlines — it is hard to force them to do so. When you care about line-based input, use fgets() or POSIX function getline() to read a line and sscanf() — or other string parsing functions — to process the line.
I'm assuming support for C99 with VLA (variable length arrays). The principles are the same without that support — the mechanics are a little different (and there are multiple options for how to do it).
Use fgets() and then strtok() with atoi().
Take the numbers as a string.
Here is one way to do it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char numbers[100];
int myn[100];
printf("Give me numbers..\n");
fgets(numbers,100,stdin);
const char s[2] = " ";
char *token;
token = strtok(numbers, s);
int i=0;
myn[i]=atoi(token);
while( token != NULL )
{
i++;
printf( " %s\n", token );
token = strtok(NULL, s);
myn[i]=atoi(token);
}
printf("You gave me: ");
for (int j=0; j<i; j++){
printf ("%d, ", myn[j]);
}
return(0);
}
The above C program does exactly what you want. At the for loop, it prints to the screen the numbers you gave from keyboard. The "problem" would be much easier by using enter instead of spaces between the numbers.
Click on the links, to see very useful details about the functions used.

!isdigit isnt working (C programming) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to create a random number guessing game that generates a random number between 1-10 and have the user guess it. It then tells the user if they're right or not. That part works fine, but the problem also asked for me to utilize the isdigit() function. I cannot get this to work for some reason. It says everything is a digit.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int main(){
srand(time(NULL));
int x;
int r;
r=(rand() %10)+1;
r=6;
printf(" Select a number between 1 and 10 \n");
scanf(" %d", &x);
if(!isdigit(x)){
if(x==r)
printf("Congratulations, you guessed correctly! \n");
else{
printf("Uh oh! You guessed the wrong number! \n");
printf("The correct guess was %d \n",r);
}
}
else{
printf("That is not a number! \n");
}
}
Is digit expects an ascii character - with '0','1','2','3' ... being values that will return non zero.
Your code is getting the actual value input (as an example 104 which would have been ascii values '1' '0' '4') and setting x to the converted integer value and then seeing if that is a ascii digit value.
You probably want to use the return code of scanf to determine whether it read a numeric value.
If, you were going to use isdigit, you would need to read the value as a string, then use isdigit on each character in the string to verify the are numbers. And then convert the string to a number using sscanf, or atoi.

This program should output a number of primes, but when i input "total" it doesn't start.Where is the mistake? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
/* Program Print Prime Numbers */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int *primes=NULL;
int trial=0;
bool found=false;
size_t total=0;
size_t count=0;
printf("\nHow many primes would you like?\n");
scanf("%d",&total);
total=(total<4?4:total);
printf("%d",total);
primes= (int*)malloc(total*sizeof(int));
if(primes==NULL)
{
printf("\nNot enough memory\n");
return 1;
}
*primes=2;
*(primes+1)=3;
*(primes+2)=5;
count=3;
trial=5;
while(count<total);
{
trial+=2;
for(size_t i=0;i<count;i++)
if(!(found=(trial % *(primes+i))))
if(found)
*(primes+count++)=trial;
}
for(size_t i=0;i<total;i++)
{
if(!(i%5))
printf("\n");
printf("%d",*(primes+i));
}
printf("\n");
return 0;
}
This a C program from a book that i use to learn C Programming.
This program doesn't work.
When it should input the "total" variable, the program continue to input values.
How many primes would you like?
4
5
10...like this
... but when i input “total” it doesn't start.Where is the mistake?
Without commenting about the other problems, the reason that it doesn't start is that it goes into an infinite loop because you say:
while(count<total);
Remove the trailing ;.
scanf() is blocking call reading input from stdin until EOL is read. This means you have to start the program, type the desired number of primes and press enter, to end the input.
EDIT:
Some clarifications:
stdin is standart input. By default it's keyboard input.
EOL means end of line. It's a character marking end of line.
Blocking call means, that the program stops until the the call is finished. Functions for input are generally speaking blocking. Very simply put, the program is removed from processor, no instructions are executed, until the call is finished, unblocking the program.
The problem isn't with scanf() or enter as some suggested - this could be easily seen by fflushing the output after the first printf.
I found the source for your code, and you forgot a little important break which does all the difference:
while(count<total)
{
trial+=2;
for(size_t i=0;i<count;i++)
if(!(found=(trial % *(primes+i))))
break; // <-------------------- HERE.
if(found)
*(primes+count++)=trial;
}
Also, as suggested, there should be no trailing semicolon after the while clause-opening.
Just press "Enter" button to force your "scanf" to return its read value

Resources