C Program won't read input from STDIN - c

I'm writing a basic statistics program as my first in pure C, and for the life of me cannot figure out this one problem. When taking input manually from the command line, it works perfectly. However, when putting in those numbers from an input file, it doesn't read any of them. Here's the source code:
statistics.c:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]){
// Create global variables, introduce program
int minimum = INT_MAX;
int maximum = INT_MIN;
int i = 0;
int count = 0;
double total = 0.0;
printf("%s\n", "Program1");
printf("%s\n", "Enter nums (0 terminates):");
scanf("%d", &i); // Scan in number
while (i!=0)
{
printf("%d\n", i); // Print the number just entered
count++; // Increment counter
total += i; // Add to total
if (i > max) {max = i;} // Check for maximum
if (i < min) {min = i;} // Check for minimum
scanf("%d", &i); // Read in the next number
}
printf("%s%d\n", "Nums entered: ", counter);
printf("%s%d%s%d\n", "range: ", min, ", ", max);
printf("%s%f\n", "mean: ", total/counter);
return EXIT_SUCCESS;
}
input.txt:
2 3 5 0
When I run ./program in the terminal, and enter those numbers manually, it gives me the expected output. But when I run ./program < input.txt, nothing happens and it gets stuck so that I have to use ^C to kill the process. Any thoughts??

The original code posted defined variables minimum, maximum, count and used variables min, max, counter respectively. Since the original code doesn't compile because of that, all we can be sure of is that your running code was not created from the source originally shown. Please do not post an approximation to the code that is causing you trouble — make sure that the code you post causes the trouble you describe (it compiles; it runs; it produces the claimed output, at least on your machine).
Here's a spell-corrected version of the code:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int min = INT_MAX;
int max = INT_MIN;
int i = 0;
int count = 0;
double total = 0.0;
printf("%s\n", "Program1");
printf("%s\n", "Enter nums (0 terminates):");
scanf("%d", &i);
while (i!=0)
{
printf("%d\n", i);
count++;
total += i;
if (i > max) {max = i;}
if (i < min) {min = i;}
scanf("%d", &i);
}
printf("%s%d\n", "Nums entered: ", count);
printf("%s%d%s%d\n", "range: ", min, ", ", max);
printf("%s%f\n", "mean: ", total/count);
return EXIT_SUCCESS;
}
When run on the file input.txt containing:
2 3 5 0
it generates the output:
Program1
Enter nums (0 terminates):
2
3
5
Nums entered: 3
range: 2, 5
mean: 3.333333
Consequently, I cannot reproduce your claimed problem, but that may be because I can't see your real code, or perhaps not your real data. If I omit the 0 from the file, then I get an infinite loop with 5 being printed each time.
Here's an alternative version with more robust input handling; it checks the return value from scanf() and avoids repeating the call, too.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int min = INT_MAX;
int max = INT_MIN;
int i = 0;
int count = 0;
double total = 0.0;
printf("%s\n", "Program1");
printf("%s\n", "Enter nums (0 terminates):");
while (scanf("%d", &i) == 1 && i != 0)
{
printf("%d\n", i);
count++;
total += i;
if (i > max)
max = i;
if (i < min)
min = i;
}
printf("Nums entered: %d\n", count);
printf("Range: %d to %d\n", min, max);
printf("Mean: %f\n", total / count);
return EXIT_SUCCESS;
}
This code works correctly on the data file without a 0 as the last number.

Related

How to fix 'Segmentation fault' while redirecting input in C

I've searched for solutions to that problem and couldn't find any that match mine.
I wrote a program that gets two arrays of integers and return the scalar product between them. It works fine when I'm submitting the input manually, but when I try to read the input from a text file, I encounter that Segmentation fault.
Edit: I'm talking about stdin redirection
I would be grateful for some help.
The code is:
#include <stdio.h>
#define MAXLIMIT 100
int scalar_product(int[], int[], int);
void set_array(int[]);
int main(){
int arr1[MAXLIMIT], arr2[MAXLIMIT];
int size, result;
set_array(arr1);
set_array(arr2);
printf("Enter the vectors' dimension: ");
scanf("%d", &size);
result = scalar_product(arr1, arr2, size);
printf("The scalar product is: %d \n", result);
return 0;
}
void set_array(int a[]){
int i;
printf("Please enter a vector with up to %d elements: \n", MAXLIMIT);
for (i = 0; i < MAXLIMIT - 1 && (scanf("%d", &a[i]) != EOF); i++);
}
int scalar_product(int a1[], int a2[], int size){
int product = 0, i;
for (i = 0; i < size; i++){
product += a1[i] * a2[i];
}
return product;
}
and the text file contains:
1 -2 3 -4
6 7 1 -2
4
HEre
void set_array(int a[]) {
int i;
printf("Please enter a vector with up to %d elements: \n", MAXLIMIT);
for (i = 0; i < MAXLIMIT - 1 && (scanf("%d", &a[i]) != EOF); i++);
}
When reading from the console you will never hit EOF (unless you enter ctrl-D which I guess you didnt) so your set_array loops just keep going, reading from the file. You read all the data in the first set_array and read nothing in the second one because you have finished the input file
the actualk failure was that you ran off the end of the file, so the scanf of size failed and you were trying to read a random sized array in the function scalar_product.
Test the return from scanf always
What you need to do is put a count in the file before the first array so you know how many items to read into arr1 and I suggest a count before the second lot too.
ie
void set_array(int a[]) {
int i;
int count = 0;
printf("Please enter how many elements you want to enter, max = %d \n", MAXLIMIT);
scanf("%d", &count);
if(count > MAXLIMIT) count = MAXLIMIT;
for (i = 0; i < count && (scanf("%d", &a[i]) != EOF); i++);
}

Some problems in coding a "guessing random number in C" under some conditions such as using input(), output()

I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}

srand() in dice game [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 8 years ago.
I've been searching the site for possible answers to this problem, and although they're all similar they don't seem to be the exact same problem that I have, which is why I've been forced to open this question. SO I need to make a dice game that is supposed to roll 2 dice ranged from 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.
For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why. I tried testing it in a seperate program and have gotten even more confused as to why I still can't get different values even with srand() being called only once at the beginning of main.(I realized that, among a few other problems were what was wrong with the functions throwCalc1 and the unnecessary throwCalc2) If I try to place rand() outside a variable, I get different values, but if I put it within a variable the values stay the same. I've tried making the variable a function and it still doesn't work as the compiler gives me an error saying "initialization makes pointer from integer without a cast"
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}
original program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}
You do this once at the top of main:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
And then expect the values to update just by calling throwCalc1() & 2 again.
Besides fixing srand(), have throwCalc1 & 2 return values into local variables instead of passing something in.
Right now you are calling throwCalc1() and throwCalc2() within your loop, but throwing away the results. You need to save those results in a pair of variables:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
After you've done this, you might notice that getcalc and getcalc2 don't need to be parameters to that function - they can just be local variables within throwResult().
In addition, your throwCalc1() and throwCalc2() functions are identical, so you can remove one them and just call the remaining one twice.
Your test function should look like:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}

how can I increment in this code

Write a program that displays a new random permutation of the integers 0 to 9 at the request of its user. For example, the program’s output could be as follows:
Your program should prints how many 7 was printed when user type no.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i , total , r;
char ans;
srand(time(NULL));
do{
for( i=0 ; i < 10 ; i++)
{
r= (rand()%(9-1+1)) + 1;
printf ("%d ",r);
}
total =0;
if (r==7) // Here how can I correct this so total will increase every time
{ // there is a 7 in the string
total++;
}
printf("\nAnother permutation: y/n?\n");
scanf(" %c",&ans);
if (ans != 'y')
{
printf("Bye!\n");
printf("The number of 7's is: %d", total);
}
}while(ans=='y');
return 1;
}
I have a problem with my code. How can I increment the 7's shown in this program after != 'y'.
Set total=0 before entering into the do-while loop, to get the correct total.

Resources