How to correctly handle scanf() - c

I have to take input in the following format
S1 S2 S3
where S1 is a character and S2,S3 are integers
for example
3
A 123 452
D 450 53
B 330 672
(where the '3' represents the number of queries)
Now I've written the following code for it :
while(i<=Q){
scanf("%c %d %d",&ch,&index,&num);
printf("%c %d %d\n",ch,index,num);
i++;
}
However, for the above shown three values I am getting the following output
0 755130840
A 123 452
123 452
with an extra line at the top and that large value (here 755130840) changing every time.
Where am I going wrong?? I even tried scanning the 3 values individually and flushing the input stream before each scan statement. However, It doesn't help either.
Given the two blank lines, I believe the newline ('\n') is being stored in some variable.How do I handle it?

Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading ch.
scanf with blank skips white space (including newlines) and reads the next character that is not white space.
Here is a code , this would be working fine.
#include <stdio.h>
int main(void) {
// your code goes here
int i =0;
int Q = 2;
char ch;
int index;
int num;
while(i<=Q){
scanf(" %c %d %d",&ch,&index,&num);
printf("%c %d %d\n",ch,index,num);
i++;
}
return 0;
}

do you want something like this?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, count, numone, numtwo;
char charip;
printf("Enter numbr of elem:\t");
scanf("%d", &num);
if (num < 0)
{
printf("Enter positive value!!!!!\n");
exit (-1);
}
count = 0;
while (count < num)
{
getchar();
scanf ("%c %d %d", &charip, &numone, &numtwo) ;
printf("%c %d %d\n", charip, numone, numtwo);
count++;
}
return 0;
}

Related

Reading a table with only one scanf

This code with C language is supposed to count all characters equal to A as well as number characters in a table .. ~~ I've started by reading the table's characters giving by the user using a for loop and then i've used another for loop to count the number of characters equal to A as well as numbers~~
THE PROBLEM is with SCANF! what should I do to write scanf one time and not twice ???
#include <stdio.h>
#include <stdlib.h>
int main()
{
char T[100] = {0};
int i=0,N=0,b=0,n=0,x=0,j=0,k=0;
printf("give the number of your table's columns \n");
scanf("%d", &N);
if (N > 0 && N <= 100) {
for (i; i < N; i++) {
scanf("%c",T[i]);
printf("give the character of the column number %d /n", i);
scanf("%c",T[i]);
}
for (i = 0; i < N; i++) {
if (T[i] == 'A') b++;
else if (T[i]<='9' && T[i]>='0') n++;
}
printf("the number of characters equal to A is %d\n",b);
printf("The number of numeric characters is %d\n",n);
}
return 0;
}
your code needing only few editing
#include <stdio.h>
#include <stdlib.h>
int main()
{
char T[100]={0};
int i=0,N=0,b=0,n=0,x=0,j=0,k=0;
printf("give the number of your table's columns:\n");
scanf(" %d", &N);
if (N > 0 && N <= 100)
{
for (i=0; i < N; i++) {
//one scanf removed
printf("give the character of the column number %d \n", i);//<--/n to \n
scanf(" %c",&T[i]); //<-- & added to store the value
}
for (i = 0; i < N; i++) {
if (T[i] == 'A') b++;
else if (T[i]<='9' && T[i]>='0') n++;
}
printf("the number of characters equal to A is %d\n",b);
printf("The number of numeric characters is %d\n",n);
}
return 0;
}
while using scanf use & so it can store value while using scanf give a space before the scanf(" %c",&T[i]);
for (i; i < N; i++) {
scanf("%c",T[i]);
printf("give the character of the column number %d /n", i);
scanf("%c",T[i]);
}
here you tried to override T[i] twice without & in scanf removing one scanf and adding & and also for(i=0;i<n;i++) will be better way to go use \n instead of /n
Is this what you were looking to do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, A_bin=0, Num_bin=0,length;
char array[100];
printf("Enter a string of numbers and letters: ");
scanf("%s",array); //Storing the Char array in "array"
length=strlen(array); //Getting the length of the Char array
for(i=0;i<=length;i++)
{
if (array[i]=='A') A_bin+=1;
else if (array[i]>= '0' && array[i]<='9') Num_bin+=1;
}
printf("The amount of 'A's in the string is: %d \n" ,A_bin);
printf("The amount of digits in the string is: %d" ,Num_bin);
return 0;
}
Instead of that story I wrote you. Here is what I think you were looking for right. This only looks for capital 'A' although could be adjusted for any characters you wanted by following the scheme. You could always adjust the array size as well for very large inputs. May have errors, play with it and see how it works. Hope the example I provided helped.
Output Example:
Enter a string of numbers and letters: AAJUR874EYRIAA
The amount of 'A's in the string is: 4
The amount of digits in the string is: 3

Getting an Array from user? C programming

My console keeps on crashing after entering a few numbers. I am trying to get an array of 10 numbers from the user thru the console and then taking count of positives, negatives, evens, and odds. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pos, neg, even, odd;
int nums[10];
printf("Give me 10 numbers: ");
pos = neg = even = odd = 0;
for(int i = 0; i < 10; i++){
scanf(" %d", nums[i]);
if(nums[i] > 0){
pos++;
if(nums[i] % 2 == 0){
even++;
}
else{
odd++;
}
}
else{
neg++;
}
}
printf("Positives: %d, Negatives: %d, Evens: %d, Odds: %d\n", pos, neg, even, odd);
return 0;
}
In your code,
scanf(" %d", nums[i]);
should be
scanf(" %d", &(nums[i]));
or,
scanf(" %d", nums+i);
as you need to pass the pointer to variable as the format specifier's argument in scanf() .
To elaborate, %d expects a pointer to int and what you're supplying is an int variable. it invokes undefined behavior.
That said,
Always check the return value of scanf() to ensure proper scanning.
int main() should be int main(void) to conform to the standard.
Modify scanf like scanf(" %d", &nums[i]);
scanf(" %d", nums[i]);
Scanf expects a pointer to a location to write to, and you're not giving it one.
Change your scanf to:
scanf(" %d", &(nums[i]));
to make your program work.
With this change I tested your program with stdin of
20 10 9 1 39 1 2 2 31 1
And recieved output:
Give me 10 numbers: Positives: 10, Negatives: 0, Evens: 4, Odds: 6
ideone of the thing for your testing purposes.
Change scanf(" %d", nums[i]); to scanf(" %d", &nums[i]);, because scanf() needs addresses. The parentheses around nums[i] isn't necessary, and may effect readability.
Also note that 0 is even, but not negative.
When scanf is usedto convert numbers, it expects a pointer to the corresponding type as argument, in your case int *:
scanf(" %d", &nums[i]);
This should get rid of your crash. scanf has a return value, namely the number of conversions made or the special value EOF to indicate the end of input. Please check it, otherwise you can't be sure that you have read a valid number.
When you look at your code, you'll notice that you don't need an array. Afterreading the number, you don't do aything with the array. You just keep a tally of odd, even and so on numbers. That means you just need a single integer to store the current number. That also extends your program nicely to inputs of any length.
Here's a variant that reads numbers until the end of input is reached (by pressing Ctrl-D or Ctrl-Z) or until a non-number is entered, e.g. "stop":
#include <stdlib.h>
#include <stdio.h>
int main()
{
int count = 0;
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
int num;
while (scanf("%d", &num) == 1) {
count++;
if (num > 0) pos++;
if (num < 0) neg++;
if (num % 2 == 0) even++;
if (num % 2 != 0) odd++;
}
printf("%d numbers, of which:\n", count);
printf(" %d positive\n", pos);
printf(" %d negative\n", neg);
printf(" %d even\n", even);
printf(" %d odd\n", odd);
return 0;
}
Change scanf statement after for loop to
scanf(" %d", &nums[i]);

Why is the output of my C program incorrect?

This is my code in C that reads data from input:
#include<string.h>
#define MAX 3
char a[MAX];
char b[MAX];
void ReadFirstNumber();
void ReadSecondNumber();
int lb,la=0;
void main()
{
ReadFirstNumber();
ReadSecondNumber();
printf("\n First Number > %d %d %d \n",a[0],a[1],a[2]);
printf(" Second Number > %d %d %d \n",b[0],b[1],b[2]);
}
void ReadFirstNumber()
{
int i=0;
printf("Enter the first number:");
scanf("%s", a);
la=strlen(a)-1;
for(i=0;i<=la;i++)
{
a[i] = a[i] -48;
}
}
void ReadSecondNumber()
{
int j=0;
printf("Enter the Second number:");
scanf("%s", b);
lb=strlen(b)-1;
for(j=0;j<=lb;j++)
{
b[j] = b[j] -48;
}
}
input first number example: 123
input second number example: 456 or any 3-digit number
//output
First Number **0**23
Second Number 456
The output for first number is 023
The first character is Zero! but the output for second number is ok.
When I comment out second function //ReadSecondNumber(); it worked perfectly!
You failed to allow enough space for the null terminator char that scanf("%s",...) writes at the end of 'strings'. Increase the value of the MAX #define. You may as well put in something sanely larger, eg 32.

C for loop iteration

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.

Let a string grow by input

following problem:
I want to make a kind of hangman game (everything in the console).
so i made a loop which turns 13 times after it runs out, the player loose (it only count down if the player inserts a wrong letter).
now, i want to show the user which letters he allready used. so the output should look like this: "you allready used: a, b, c, g..." and so on. So after every try, the line grow by one letter (the input letter of course).
i tried strcpy, but it only makes random letters which i never put in, and it doesn't grow, so how can i handle this?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <ctype.h>
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
char word[81], used[14];
int wrong=0, laenge, _, i;
char input;
SetConsoleTitle(" Guess me if u Can! ");
//printf("\n\n spielst du mit einem Freund oder alleine?"); /*for later
//printf(" \n\n [1] alleine"
// " \n\n [2] mit einem Freund"); */
printf("\n\n please insert a word (max. 80 characters): \n\n");
gets(word);
laenge=strlen(word);
printf("\n\n this word has %i characters.\n\n",laenge);
for(i=0; i<13; i++)
{
// for(_=0; _<laenge; _++) /*ignore this this is also for later
// printf(" _");
// printf("\n"); */
gotoxy(10,10);
printf("\n\n please insert a letter now: ");
input=getch();
strcpy(used, &input);
printf("\n\n The following characters are allready used: %c ", used);
if(strchr(word, input)){
printf("\n\n %c is in the word\t\t\t\t\t\t\n\n");
i--;
}
else{
printf("\n\n the letter %c is wrong!\n");
wrong++;
printf(" you have %i try",13-wrong);
}
}
system("cls");
printf("\n\n to many tries.\n\n");
system("Pause");
}
First, you should fill up used with 0 characters to ensure it is always properly terminated:
memset(used, 0, 14);
Then, add a new character to it like this:
used[i] = input;
Also, as #Fred noted, you should use the proper format specifier %s in the printf call.
As already said here you should fill used with zeros, something like used[14] = {0};
Then I think the line printf("\n\n The following characters are allready used: %c ", used); should be printf("\n\n The following characters are allready used: %s ", used);, notice the "%s" you're printing a string.
If you know the maximum size, you can create a buffer with that maximum size, and then append to it. In this case you do know the maximum size, as there are only 26 letters in the alphabet. So the maximum length of the string is the length of whatever text you put at the beginning, plus 26 times the number of characters you'll use for each letter. I count 18 in the initial string. Remember to add one for the null byte terminator at the end. For each letter you have the letter, a comma, and a space, so the max length is 18 + 26*3 + 1 = 97 if I did the arithmetic right.
So you could write something like:
char used[96];
strcpy(used,"You already used: ");
int first=TRUE;
... whatever other work ...
... let's say we get the character in variable "c" ...
// Add comma after previous entry, but only if not first
if (!first)
{
first=FALSE;
strcat(used,", ");
}
// turn character into a string
char usedchar[2];
usedchar[0]=c;
usedchar[1]='\0';
// Append to working string
strcat(used,usedchar);

Resources