Unexpected output when using scanf("%d\n") [duplicate] - c

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 3 years ago.
The output I expect after reading 3 times is the sum of those three numbers,
but when reading the numbers there is a problem with the printing.
for (i = 0; i < TAMANIO; i++) {
scanf("%d\n",&ar[i]);
printf("numero: %d\n",ar[i]); //print numbers
}
If you need full code.
#include <stdio.h>
#define TAMANIO 3
//prototipo de funciones
void pri();
int pro(int a, int b, int c);
int main () {
pri(); //Ask for numbers
int i; //counter
int ar[TAMANIO];
for (i = 0; i < TAMANIO; i++) {
scanf("%d\n",&ar[i]);
printf("numero: %d\n",ar[i]); //print numbers
}
printf("suma de numeros: %d\n", pro(ar[0],ar[1],ar[2])); //send number to function and print
return 0;
}
void pri(){
//write numbers
printf("Escriba los 3 numeros a ser operados : \n");
}
int pro(int a, int b, int c) {
int sum;
sum = a + b + c;
return sum;
}
I expect when reading:
"enter numbers"
1
number : 1
2
number : 2
3
number : 3
sum : 6
[ More Scanf() info ] What is the effect of trailing white space in a scanf() format string?

You could try changing scanf("%d\n",&ar[i]); to scanf("%d",&ar[i]);, because it will try to read newline break too in a loop.
Simply remove \n from the scan

You need to remove the \n from scanf.
for (i = 0; i < TAMANIO; i++) {
scanf("%d",&ar[i]);
printf("numero: %d\n",ar[i]); //print numbers(here is the problem)
}

Related

Find the nth number in fibonacci using c

This task is to find fibanocci of n numbers. TASK: 1.To find fibanocci of n numbers. 2.Use variables n,first=0,second=1,next,c. INPUT FORMAT: Use printf statement. Use scanf to get the number n. Use FOR loop. Use IF....ELSE loop statement. OUTPUT FORMAT: Use printf statement to print the output SAMPLE INPUT: 2 SAMPLE OUTPUT: 3(From HackerRank)
I tried solving above but they asked for input 2 output should be 3 But They also asked output 01 on input 1.Can You tell me How to proceed?
#include<stdio.h>
int fib(int n)
{
int f[n+1];
int i;
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++)
{
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
int main ()
{
int n;
scanf("%d",&n);
printf("%02d", fib(n));
getchar();
return 0;
}
The reason you get 01 is you use a %02d conversion specifier.
You should use a plain %d conversion to get 1 for 1 and 1 etc...

Why should i use a space before %c while taking input into an array? [duplicate]

This question already has answers here:
what is the purpose of putting a space in scanf like this scanf(" %c",&ch) in place of scanf("%c",&ch)? [duplicate]
(6 answers)
Closed 6 years ago.
I have just written a program to reverse a word. I have first compiled the program as follows:
//This program will reverse a given word
#include <stdio.h>
int main()
{
int letters, i, j;
printf("Enter the number of letters in your word: ");
scanf("%d", &letters);
int word[letters];
printf("Enter %d Letters: ", letters);
for( i = 0; i < letters; i++){
scanf("%c", &word[i]);
}
for( j = i - 1; j >= 0; j-- ){
printf("%c", word[j]);
}
return 0;
}
Then, I inputted 5 to store in letters and the word "rubel" (ignore the inverted comma) to reverse. The expected output was "lebur". But unfortunately i got ebur. then i recompiled the code as below:
//This program will reverse a given word
#include <stdio.h>
int main()
{
int letters, i, j;
printf("Enter the number of letters in your word: ");
scanf("%d", &letters);
int word[letters];
printf("Enter %d Letters: ", letters);
for( i = 0; i < letters; i++){
scanf(" %c", &word[i]);
}
for( j = i - 1; j >= 0; j-- ){
printf("%c", word[j]);
}
return 0;
}
This time i got expected output which is "lebur". Now, my question is what was wrong before that i didn't get expected output and what have i just done by putting a space that this time i got the expected result. Thanks in advance.
In the first case word[0] became \n (you entered 5\n). In the second case the \n was skipped because you told scanf to skip whitespace characters (by ).

C scanf in loop continues automaticly without input

I'm trying to get input in an array, I expect input like the following.
5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)
So we get an array deeln[2][5] in this example. I try to get it with the following code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
scanf("%s", temp);
for(cj = 0; cj < k; cj++){
deeln[ci][cj] = temp[cj*2]-'0';
}
}
//loop while.
}
But i've got a problem, whenever i try to input, the program runs automaticly without getting any input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.
What to do? Has it something to do with pointers or am i using scanf wrong?
UPDATE:
If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.
The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp = 0;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;
//get input
scanf("%i", &k);
scanf("%i", &d);
char temp[20];
int deeln[d][k];
memset(deeln, 0 , sizeof(deeln));
memset(temp, 0 , sizeof(temp));
for(ci = 0; ci < d; ci++){
fgets(temp, 20, stdin);
for(cj = 0; cj < k; cj++){
ta = cj*2;
deeln[ci][cj] = temp[ta]-'0';
}
}
//loop while.
return 1;
}
Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!
Two places to look:
1)
cj = 0;//initialize cj before using here
scanf("%i", &temp[cj]);//temp is both an array, and an int. Fix your format specifier,
//and use an index operator - temp[?] (not sure I am using the right index)
2)
deeln[ci][cj] = temp[cj*2]-'0'; //fix your logic here (array index will be exceeded)
An example of working code...
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
for(cj = 0; cj < k; cj++){
if(scanf("%i", &temp[cj]) != EOF)
{
deeln[ci][cj] = temp[cj]-'0';
}
else deeln[ci][cj] = -1;
}
}
getchar();
//loop while.
}
you can play with the index of temp[cj] to make it what you actually want, but I assume you are intending to read from stdin, then populate deeln[][] with that value, for each scanf.
If you want to parse a string containing spaces and digets, "1 3 8 5 3", you could use strtok()
But your code as it is is not reading a string in, it is reading integers.
This is not perfect, you will have to do some debug, but will illustrate strtok(). You have to enter spaces between each digit after indices are selected: i.e.:
3
3
4 6 8
2 4 7
1 2 8
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
char inStr[d][k*5]; //space for up to k 3 digit numbers with 1 space each
char *buf=0;
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
if(scanf("%s ", inStr[ci]) != EOF)
{
buf = strtok(inStr[ci], " ");
cj = 0;
while(buf && (cj < k))
{
deeln[ci][cj] = atoi(buf);
cj++;
}
}
}
//getchar();waits for user input, pauses execution
}

Check for Character instead of Integer [duplicate]

This question already has answers here:
Check if a value from scanf is a number?
(2 answers)
Closed 9 years ago.
my program adds numbers entered by the user. It runs and works great until a character is entered instead of an integer. Is there a simple way to make sure only integers are entered from the keyboard?
Here is my code.
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
scanf("%d",&TotalOfNumbers);
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}
You need to check the return value of scanf. If the input was a valid number, it will return 1. If the input was not a valid number, it will return something else. Here is your code modified to put the checks in.
#include<stdio.h>
#include <stdlib.h>
int get_number()
{
int num;
int ret;
ret = scanf("%d", &num);
if (ret != 1) {
printf("bad number\n");
exit(EXIT_FAILURE);
}
return num;
}
int main(int argc, char **argv)
{
int n, sum = 0, i, TotalOfNumbers;
printf("Enter the number of integers you want to add\n");
n = get_number();
printf("Enter %d integers\n",n);
for (i = 1; i <= n; i++)
{
TotalOfNumbers = get_number();
sum = sum + TotalOfNumbers;
}
printf("Sum of entered integers = %d\n",sum);
return 0;
}
Check the ferror state on the input stream
scanf("%d",&TotalOfNumbers);
if(!ferror(stdin)){
sum = sum + TotalOfNumbers;
}
In addition to posted answer, there options not general as posted, but quicker.
First if you want to skip some final set of characters.In following example all letters,! and + will be skiped
int n;
scanf("%*[a-zA-Z!+]%d",&n);
printf("\n%d",n);
for input
weweqewqQQWWW!!!!+++3332
the output is
3332
Next option is to use buffer wich allowed to read everything untill number is met, and then read the number. The disadvantage is that buffer size is limited
char buf[25];
int n;
scanf("%[^0-9]%d",buf,&n);
printf("\n%d",n);
For input
fgfuf#$#^^#^##4565
Output
4565

scanf requires more inputs than requested [duplicate]

This question already has answers here:
Store data in array from input [duplicate]
(2 answers)
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 9 years ago.
I'm trying to get 5 float values from the user using scanf, the problem is the user is required to input 6 values for the program to complete.
Although I know I shouldn't use scanf, it bothers me that there's something I can't grasp about it. Any insights, any advice on how to fix it whilst using scanf?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0 , j = 0;
char buf[128] = {0};
float numbers[5] = {0.0};
float keep = 0.0;
printf("Please input 5 numbers : \n");
for (i = 0; i < 5; i++)
{
scanf("%f\n", &numbers[i]);
}
printf("Done!");
Thanks,
MIIJ
you must remove \n in scanf() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0 , j = 0;
char buf[128] = {0};
float numbers[5] = {0.0};
float keep = 0.0;
printf("Please input 5 numbers : \n");
for (i = 0; i < 5; i++)
{
scanf("%f", &numbers[i]);
printf("number %i is %f \n",i,numbers[i]);
}
printf("Done!");
return 0;
}
scanf("%f\n", &numbers[i]); should be scanf("%f", &numbers[i]);

Resources