I'm extremely new to C coding and i'm wondering why this is crashing like this? After I input a value and press enter, my program instantly crashes. I remember learning there are times when you use a & with an array in the scanf line and sometimes you don't. So when I remove the & it crashes instantly. I'm not sure how to troubleshoot this problem and would appreciate help.
What i'm trying to accomplish:
"Write a program that asks the user to enter a sequence of integers terminated by 0 ( the last number is 0) and prints all the numbers entered on one line."
The program crashes before I can enter the other variables. I was not done coding but since it keeps crashing instantly I can't go further.
int main () {
int ru[1000];
int read;
int nums;
int counts;
printf("Enter integers, press 0 to end user input \n");
while (nums>0) {
scanf("%d",&ru[nums]);
if (nums==0)
printf("%d ", ru[nums]);
}
system("pause>nul");
return 0;
}
As noted by several people already, you don't ever assign a value to nums at any point in your code, but make use of it in several places.
You should populate nums and whilst it's more than zero (this should probably be not equal to zero if you want to also include negative integers), store it's value into your array. You can track where you are in the array using another variable (I've picked the read one that you'd already declared), making sure that it is first initialised to 0.
Once the while loop is terminated, either by nums being zero or you filling up the array, you can then print out the numbers you've collected.
int main (void) {
int ru[1000];
int read=0;
int nums;
int counts;
printf("Enter integers, press 0 to end user input \n");
scanf("%d",&nums);
while ((nums>0)&&(read<1000)) {
ru[read++]=nums;
scanf("%d",&nums);
}
for(counts=0;counts<read;counts++) {
printf("%d ",ru[counts]);
}
printf("\n");
system("pause>nul");
return 0;
}
The scanf() you are using as the following prototype:
int scanf(const char *format, ...);
you should give the de pointer to the buffer variable as a parameter but your are giving a pointer to an array (pointer to a pointer).:
scanf("%d",&ru[nums]);
A solution to your problem might be:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int ru[1000];
int i = 0;
printf("Enter integers, press 0 to end user input \n");
do
{
scanf("%d",&ru[i]);
}while (ru[i]!= 0 && i++ < 1000);
for(i = 0; ru[i] != 0 ; i++)
printf("%d ", ru[i]);
return EXIT_SUCCESS;
}
Related
I am relatively new to C, I have to do it for school unfortunately and I am having issues with it at the easiest exercises.
Here I have to check if a number is in a certain interval, for example between 4 and 6. I made it like this.
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%s", i);
if (i>4 && i<6){
printf("%s Value is in first interval\n", i);
}
}
The scanf to enter the number and check if it is in the interval. But even if I enter a number that is part of it, for example 5, the printf doesn't do anything. I tried also to add an else statement for numbers outside the interval, but also there the printf did not change anything.
It is because you have declared i variable as int and you are taking input as string so when it is checking condition it is getting null value in i variable and not able to enter if block check below code
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%d",&i);
if (i>4 && i<6){
printf("%d Value is in first interval\n", i);
}
}
try compiling your code without if condition i variable will return a null value
I’m brand new to programming. I ‘m working on a homework assignment in order to help us understand scanf and arrays. The program is supposed to ask the user to input an unknown set of numbers. Each set of numbers should be separated by a space like below without hitting enter.
14 15 16
The user can also input numbers on a separate line instead using spaces, but again on the last number inputed the user isn’t supposed to hit enter.
12 13
44 55
5
The user should hit ctrl-d to indicate end of input. The program should display the number of elements entered by the user, along with displaying the numbers the user entered. I have been reading around and think I have a basic concept of how scanf works, but I am still having some difficulty. The code kind of works. However, if the user just enters the numbers on one line they need to hit ctrl-d three times in order for it to exit the loop and display the information.
From what I have found online and understand, I think it’s not working because the user hasn’t hit return, so the input hasn’t been flushed into the stdin. So if I'm understanding correctly, the first time I hit ctrl-d it while flush the input. Then the second time I hit ctrl-d it will finally put the EOF into the stream and the third time it will finally read the -1 produced by the EOF and exit the loop.
Is there anyway to force the input stream once ctrl-d is entered.
#include <stdio.h>
int main()
{
int numbers[20];
int i = 0, count, result, n;
int flag = 0;
printf("Please enter a seiries of numbers:\n");
while (flag == 0)
{
result = scanf("%d", &n); //scan user input into n variable along with getting scanf return value and storing in result variable
printf("result =%i \n", result); //Just printing scanf return value to insure it doing what I think it should be doing
if (result == 1)
{
numbers[i] = n; //if scanf return value is 1 places value of n into first element of array
i++; //used to increment my array
flag = 0;//keeps value of flag equal to 0 in order to stay in loop
}
if(result == -1) //checks to see if result = to -1 should be value returned if cntl +d is entered
{
flag = 1; //sets flag to 1 when cntrl +d is entered in order to exit loop.
}
}
for (count = 0 ; count < i ; count++) //loop to print I which is representing number of user inputs and the actual numbers entered by the user.
{
printf("\ni= %i numbers= %i\n", i, numbers[count]);
}
return 0;
}
I won't give you a solution directly, but will try to help you improve coding in C. The more you work with C the more you will find out that one can write pretty compact code, once the language is mastered.
You can omit flag because it depends on result.
And you could omit result because it is just the return value of scanf.
You can omit n and use numbers array directly.
And you could make use of the preprocessor to use a constant number (often for array sizes as in your case).
Have a look at this. Maybe it helps you get an idea:
#include <stdio.h>
#define COUNT 20
main() {
int numbers[COUNT];
int i;
i = 0;
while (scanf("%d", &numbers[i]) == 1 && i < COUNT)
printf("\t%d\n", numbers[i++]);
return 0;
}
P.S.:
I recommend getting acquainted with the different ways of accessing an array and reading about pointers. The have a very close relationship really.
Address of first element in array : numbers
Access ith element of array : numbers[i]
Equivalently : *(numbers + i)
Another equivalence : *(i+numbers)
Surprise, but equivalent again : i[numbers]
Address of ith element of array : &numbers[i]
K&R is a great resource of information and learning.
So I understand the basic concepts of making a simple calculator, such as asking user for two int values a,b and then asking them which operating sign they want to use. But I want to create something more complex and usable.
My method is to scan int values and operator signs separately, so first it will scan into int, then into string??? the input would be something like:
1 (enter)
'/' (enter)
2 (enter)
'+' (enter)
4(enter) and then the user can press x to end and calculate.
int main()
{
int array_int[30];
char array_operators[30];
int hold_value = 0;
int i = 0;
printf("Enter your calculations, press enter after each number and operator is entered \n");
while(1==1){
scanf("%i",&hold_value); //Use this to decide which array to put it in.
if(isdigit(hold_value)){
array_int[i] = hold value // Check if input will be an int or char to decide which array to store it in??
}
I still need a way of ending the loop on user input, and I know that my logic that I put into the conditional makes no sense, but I'm new to C and I don't know all my options. Hopefully my goals were stated clear enough for you guys to help me out. Thanks
Altering your current code,
int main()
{
int array_int[30]={0};
char array_operators[30]={0}; //Initialize variables. It is a good practice
char hold_value; //hold value must be a char
int i = 0, j = 0;
printf("Enter your calculations, press enter after each number and operator is entered, press Q to quit \n");
while(1){
scanf(" %c",&hold_value); //Note the space before %c. It skips whitespace characters
if(hold_value=='Q') //break the loop if character is Q
break;
if(isdigit(hold_value)){ // If input is a digit
array_int[i++] = hold_value-'0'; //Store the integer in array_int
}
else{ //Input is a character
array_operators[j++] = hold_value;
}
}
//Calculate from here
return 0;
}
If you want to end the loop when there is nothing to return just use return(0).
If you want to end the programm than exit(0).
Also, please check the following:
http://forum.codecall.net/topic/50733-very-simple-c-calculator/
So I'm trying to find the sum of an unknown amount of user-input numbers. Here's my code
int main()
{
int tmp1 = 1;
int tmp2 = 1;
int total = 0;
printf("Enter numbers for a sum: ");
tmp2 = scanf(" %d", &tmp1);
while(tmp2 > 0){
total+=tmp1;
tmp2 = scanf(" %d", &tmp1);
}
printf("total is %d", total);
return 0;
}
It gets stuck in an endless loop, and then once i hit ctrl-c to end it, it prints the correct sum. So what I'm doing wrong is how will i know when it's done scanning all the integers, and for the loop to end; since i'm not doing it correctly now
Decided to make it stop via ctrl d, and its acceptable. thanks
In your question, it is not clear how you expect your programme to understand that there won't be anymore numbers to input. Shall it be through a specific character? Or shall it just get a line of space-separated numbers and respond with a sum?
From your code, my most sensible guess is: You want it to understand that there won't be any more numbers to add, whenever it encounters a non-digital character. My guess is so, because this is almost exactly what your code does by checking the return value from scanf.
First of all, you have to change that tmp inside your loop into tmp1 because there isn't such a variable as tmp declared. edit: well, never mind
Then try running your programme, putting in any amount of white-space (space, tab or new-line) separated numbers, and then any non-digital character you like. May be a T for example, or ThoAppelsin, it won't matter. Programme won't get beyond the first character, in fact, not even beyond the first character. After that, you shall see that the numbers have been properly added together.
Since you're confused about a non-existent infinite-loop, my second guess is that you might be actually hoping it to get a single line of space-delimited numbers, and have the sum printed; and misinterpret your programme as "in infinite loop" while it merely expects further input from you, just like it does at the very beginning.
You won't get a 0 from non-redirected scanf("%d", &var);, unless you feed it with something that doesn't match to the format string to cause abnormal termination. If there's nothing left in the input stream to consume, it will just wait for more input. But say you give an 'a' to it, then all it can do is to give up and return zero, because it couldn't do a single assignment.
If you really are hoping to have a single line of numbers, then the minimal change I could offer would be something like this:
int main(void)
{
int tmp1 = 1;
char tmp2 = 0;
int total = 0;
printf("Enter numbers for a sum: ");
scanf("%d%c", &tmp1, &tmp2);
while(tmp2 == ' '){
total+=tmp1;
scanf("%d%c", &tmp1, &tmp2);
}
printf("total is %d", total);
return 0;
}
Of course, this approach has many vulnerabilities. However, if user is to input strictly a sequence like:
3 66 2 10 6
// mind the new-line
It will work fine. But if I'm allowed to change more than minimal, this is how I would do it:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
int LastNumber = 0;
int UpcomingCharacter = 0;
int Total = 0;
printf("Enter numbers for a sum: ");
while(scanf("%d%*[ \t]", &LastNumber) == 1)
{
Total += LastNumber;
UpcomingCharacter = getchar( );
if (!isdigit(UpcomingCharacter)) // eliminates a possible EOF return as well
break;
if (ungetch(UpcomingCharacter, stdin) != UpcomingCharacter)
{
fprintf(stderr, "%d: unexpected error with ungetch\n", __LINE__);
return EXIT_FAILURE;
}
}
printf("total is %d", Total);
return EXIT_SUCCESS;
}
Which should work fine on any whitespace-delimited sequence of numbers, excluding the new-lines of course.
this is a menu driven program having two functions. everything works fine if i enter numbers but when i enter character it runs infinite times sometimes :(
like when i enter integers it works fine and if i enter char it shows some junk value and then try again option is showed and i again enter char it runs infinite times
#include<stdio.h>
#include<conio.h>
#include<math.h>
void cal()
{
int x,y,z;
printf("enter two numbers\n");
scanf("%d%d",&x,&y);
z=x+y;
printf("%d\n",z);
}
void mul()
{
int x,y,z;
printf("enter two numbers\n");
scanf("%d%d",&x,&y);
z=x*y;
printf("%d\n",z);
}
void main()
{
int x,c;
clrscr();
menu :
printf("1.sum\n");
printf("2.mul\n");
printf("enter choice\n");
scanf("%d",&x);
switch(x)
{
case 1:cal();break;
case 2:mul();break;
default :printf("try again\n");
}
printf("press 5 to run another function\n");
scanf("%d",&c);
if(c==5)
{
goto menu;
}
getch();
}
You could try updating your gcc compiler. I ran the code on gcc 4.8 and the code terminated well for characters as well.
Otherwise if you really want to handle characters as well you take an input using a char pointer (string that is ) and then using atoi(str) store it in an int variable and then process it. And you can check : if the user enters characters ( using isalpha() ) then terminate the code.
Sample Code : (ran well enough)
char *s = malloc(64);
scanf("%s",s);
if(isalpha(s[0]))
return ;
else
int x = atoi(s);
int sum = x + 1; //or whatever manipulations you need to do
"when i enter character it runs infinite times sometimes ..."
All the code that tries to read an int uses the following of some sort. When non-numeric data is entered, scanf("%d", ... does not consume that IO (leaving it for the next IO operation), does not set c to any value, and then returns a 0 (which is not tested). At that point c has whatever value it had before the scanf() call. Since c was not initialized, its value could be anything - hence undefined behavior as suggested by #BLUEPIXY
int c;
...
scanf("%d",&c);
Since the non-numic data is left for the next IO and the next IO could be another scanf("%d", code is stuck in a rut - infinite loop.
To best fix, initialize variables, get the user input via fgets() and detemrine the value via sscanf() or strtol().
int c = 0;
char buf[80];
if (fget(buf, sizeof buf, stdin) == NULL) Handle_EOForIOerror();
if (sscanf(buf, "%d",&c) != 1) Handle_NonNumericInpupt();