This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 3 years ago.
int main()
{
float T[100];
float *pt=T;
float suma = 0, srednia, zmienna;
int rozmiar;
printf("How many numbers would you like to put in: ");
scanf(" %d", &rozmiar);
int dzielnik = rozmiar;
printf("\n Enter the number: \n");
for(int i = 0;i<rozmiar;i++)
{
printf("\n i = %d", i );
scanf("%99f\n", &zmienna);
*(pt+i) = zmienna;
}
return 0;
}
This is my code. The idea is simple. I have an array; I want to scan how many numbers I want to put into the array and then put numbers into array. I don't know why but scanf ignores the second variable that I put in array.
If I put "2" in first scanf, program wants 3 variables from me.
My output should be like this:
How many numbers would you like to put in: 2
Enter the number:
i = 0
2 (my number)
i=1
3 (my number)
but it's actually like this:
How many numbers would you like to put in: 2
Enter the number:
i = 0
1 (my number)
2 (my number)
i = 1
3 (my number)
The specific problem you were having is with scanf: putting a \n is generally a bad idea because entering a newline is generally how you send off a line of characters to the program. Use '\n' liberally in printf and "never" with scanf.
Here's my modified version. I removed the pointer shenanigans because indexing into the array is simpler and better, and also initialized the array which you should always do:
#include <stdio.h>
int main() {
float T[100] = {0}; // Used to not be initialized.
float suma = 0, zmienna;
int rozmiar;
printf("How many numbers would you like to put in: ");
scanf("%d", &rozmiar);
printf("\n Enter the number: \n");
for (int i = 0; i<rozmiar; i++) {
printf("\n i = %d", i);
scanf("%f", &zmienna);
T[i] = zmienna;
}
return 0;
}
Related
I need my code to print out
Input the number of values: Input the values between 0 and 9 (separated by space):
your histogram:
0-3
1-2
2-0
etc.
but it looks nothing like that? help
#include<stdio.h>
void printStars(int n){
int i;
for(i = 0;i<n;i++){
printf("*");
}
printf("\n");
}
int main() {
int i,n = 10;
int input[100];
int hist[10] = {0};
printf("Input the amount of values: ");
scanf("%d",&n);
printf("Input the values between 0 and 9 (separated by space): ");
for(i = 0;i<n;i++){
scanf("%d",&input[i]);
}
for(i = 0;i<n;i++){
hist[input[i]]++;
}
printf("\n\nYour histogram: ");
for(i = 0;i<10;i++){
printf("%d - %d\n",i,hist[i]);
}
return 0;
}
I'm assuming the printStars(int n) method is supposed to replace count of each number,
e.g. instead of 0 - 3 you would see 0 - * * *
If this is the case, you will want to change the for loop on line 25 to this:
for(i = 0; i < 10; i++){
printf("%d - ",i);
printStars(hist[i]);
}
Also, on line 24, you need an additional \n at the end of the printf to put your 0-count for the histogram on its own line: printf("\n\nYour Histogram: \n");
Don't forget to make sure your input is within bounds as well, as you never check if int n is within bounds of input[]. Speaking of this, why is n instantiated to 10, then immediately scanned into for input without use of n = 10?
If you aren't seeing any output on run, try typing input immediately. It's possible that requesting input is clearing the current line printed to.
printf("Input the amount of values: ");
scanf("%d",&n);
In this case, since there is no \n at the end of the printf and a scanf is immediately called, the input request might be clearing the output line and requesting input. Adding a \n to the end of printf might correct this, if it is the problem you're having.
Other than this, there doesn't seem to be any major problems.
your code is working. What format do you get and what format do you expect ? Personally, I have the
0-3
1-2
2-0
format
Beginner programming including arrays and I'm having trouble just getting user input for the arrays. The printf functions I've included are just to check whether my arrays are working, the larger program I'm writing just needs to use these two arrays.
The input for the char array seems to work fine, I've tried a couple of different methods. However, the int array doesn't seem to work using the same diversity of methods I've used successfully with the char array. Not sure what I'm missing. Below is the code and the output when I run the program:
int main()
{
char grades[5]; // create array to store letter grades
int hours[5]; // array to store hours
puts("Please enter letter grades:"); // Input letter grades using fgets
fgets(grades, 5, stdin);
printf("Letter grade for course 3 is %c.\n", grades[2]);
int x = 0;
puts("Please enter course hours:\n");
for (x = 0; x < 5; x++)
{
scanf("%d", &hours[x]);
}
printf("Course hours for course 2 are: %d.\n", hours[1]);
return 0;
}
Output of this code:
Please enter letter grades:
ABCDF <- user input
Letter grade for course 3 is C.
Please enter course hours:
Course hours for course 2 are: -858993460.
Press any key to continue . . .
fgets(grades, 5, stdin); captures ABCD of the input leaving F in the input stream. scanf("%d", &hours[x]); can't parse an int from F though it tries five times. Each failure leaves the F in the input stream.
Make buffers large enough for typical input.
Use fgets for all input. Parse with sscanf or others. Use the return of sscanf to make sure the parsing was successful.
#include <stdio.h>
int main( void)
{
char grades[50] = ""; // create array to store letter grades
char line[50] = "";
int hours[5] = { 0}; // array to store hours
int result = 0;
puts("Please enter letter grades:"); // Input letter grades using fgets
fgets(grades, sizeof grades, stdin);
printf("Letter grade for course 3 is %c.\n", grades[2]);
int x = 0;
for (x = 0; x < 5; x++)
{
do {
printf("Please enter course %d hours:\n", x + 1);
fgets ( line, sizeof line, stdin);
result = sscanf( line, "%d", &hours[x]);
if ( result == EOF) {
printf ( "EOF\n");
return 0;
}
} while ( result != 1);
}
printf("Course hours for course 2 are: %d.\n", hours[1]);
return 0;
}
This question already has answers here:
Accepting any number of inputs from scanf function
(6 answers)
Closed 5 years ago.
If I want to get input 3 numbers, I can write code like this:
scanf("%d %d %d", &a, &b, &c);
but how can I dynamically get the number of inputs from one line?
For example, if user enters N(number), then I have to get N integer number inputs from one line like above.
The input and output should be :
how many do you want to enter: 5
1 2 3 4 5
sum: 15
Since scanf returns the amount of variables filled you can loop until scanf has no more value to read or the count is matched:
int count = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);
int val = 0;
int sum = 0;
int i = 0;
while(scanf("%d ", &val) == 1 && i++ < count)
sum += val;
As you don't know the size of inputs previously it's better to create a dynamic array based on the input size provided by the user. Input the size of the array and create an array of that size. Then you can easily loop through the array and do whatever you want with it.
int count = 0, sum = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);
int *num = malloc(sizeof(int)*count);
for(int i = 0; i < count; i++) {
scanf("%d ", &num[i]);
//sum += num[i];
}
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.
Basically I have a C program where the user inputs a number (eg. 4). What that is defining is the number of integers that will go into an array (maximum of 10). However I want the user to be able to input them as "1 5 2 6" (for example). I.e. as a white space delimited list.
So far:
#include<stdio.h>;
int main()
{
int no, *noArray[10];
printf("Enter no. of variables for array");
scanf("%d", &no);
printf("Enter the %d values of the array", no);
//this is where I want the scanf to be generated automatically. eg:
scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);
return 0;
}
Not sure how I might do this?
Thanks
scanf automatically consumes any whitespace that comes before the format specifier/percentage sign (except in the case of %c, which consumes one character at a time, including whitespace). This means that a line like:
scanf("%d", &no);
actually reads and ignores all the whitespace before the integer you want to read. So you can easily read an arbitrary number of integers separated by whitespace using a for loop:
for(int i = 0; i < no; i++) {
scanf("%d", &noArray[i]);
}
Note that noArray should be an array of ints and you need to pass the address of each element to scanf, as mentioned above. Also you shouldn't have a semicolon after your #include statement. The compiler should give you a warning if not an error for that.
#include <stdio.h>
int main(int argc,char *argv[])
{
int no,noArray[10];
int i = 0;
scanf("%d",&no);
while(no > 10)
{
printf("The no must be smaller than 10,please input again\n");
scanf("%d",&no);
}
for(i = 0;i < no;i++)
{
scanf("%d",&noArray[i]);
}
return 0;
}
You can try it like this.