c program not taking input properly and producding wrong output - c

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,x,i,j;
char st[50];
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&n,&x);
for(j=0;j<n;j++)
{
scanf("%c",&st[j]);
if(st[j]=='A')
x=x*1;
if(st[j]=='B')
x=x*-1;
}
printf("%d",x);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
Input to the code is in the form:
t
n x
some_string_having_A_and_B
Sample:
1
3 10
ABA
expected output
-10
actual output
10
This code gives -10 if number of B is odd and 10 if number of B is even. I know the correct and optimal way of writing the program but I can't figure out, why this code is producing wrong ouput.

The first scanf("%c") reads the previous ENTER in the input stream.
Suggestion for fast fix: use a space inside the specification to have scanf ignore whitespace (Enter is whitespace).
Try
if (scanf(" %c", &st[j]) != 1) /* error */;
// ^ ignore whitespace
Suggestion for better fix: read all user input with fgets().
char line[100];
...
fgets(line, sizeof line, stdin);
if (sscanf(line, "%c", &st[j]) != 1) /* error */;

if(st[j]=='B')
x=x*-1;// you need to put bracket here.on -1
//correct form is x=x*(-1)
}
//corrected code starts from here
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,x,i,j;
char st[50];
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&n,&x);
for(j=0;j<n;j++)
{
scanf("%c",&st[j]);
if(st[j]=='A')
x=x*1;
if(st[j]=='B')
x=x*(-1);// you need to put bracket here.on -1
}
printf("%d",x);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}

Related

Check if input is a number [duplicate]

This question already has answers here:
Check if input is integer type in C
(16 answers)
Closed 5 years ago.
I have a bit of code that is supposed to get numbers from input until EOF and put them inside an array.
#include <stdio.h>
int main(){
int numbers[250000],i,m=0;
while(scanf("%d",&i)!=EOF){
numbers[m]=i;
m++;
}
}
My problem is that I need to check if the input is valid (if it is a number). If it is not a number I need to print out a message that says something along the lines "Wrong input" and end the program.
Can somebody please help me?
PS. I know that this question has been asked several time, I have googled, but I have not been able to figure out from the answers how to adapt the code to my situation. So, sorry if the question seems redundant.
scanf's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully, scanf will return 1.
#include <stdio.h>
int main(){
int numbers[250000],i,m=0;
int itemsRead = 0;
while(itemsRead = scanf("%d",&i) != EOF){
if (itemsRead != 1)
{
printf("Wrong input");
return 0;
}
numbers[m]=i;
m++;
}
}
Shortening #gssamaras code, you can have something simpler, like this
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
int numbers[250000],i,m=0;
char temp;
while(scanf("%c",&temp)!=EOF)
{
if(!isdigit(temp)))
{
printf("Wrong input");
break;
}
numbers[m]=atoi(temp);
m++;
}
}
You need to read the input as a string, validate that its context is actually a number, and then assign it to the array's cell, like this:
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#define MAXINPUT 100
int main() {
int numbers[250000],m=0;
char input[MAXINPUT] = "";
while(scanf ("%s", input)!=EOF) {
for (size_t i = 0; i < strlen(input); i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
// here we know that 'input' is a number
numbers[m] = atoi (input);
m++;
}
return 0;
}
PS: I would use fgets() instead of scanf().

C: Scanning While not EOF Loop Unexpected Results

I know there are many questions on the same topic of scanf until EOF is reached, but here's a particular case I haven't seen. Suppose I want to make a C program where the user enters a single character, and the program prints back the character and the number of times the user has entered a character until they press CTRL+D (EOF)
This is what I have:
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
printf("time:%d, char:%c\n",i,thing);
i++;
}
return 0;
}
However, the output is not as expected. It's the following:
f
time:0, char:f
time:1, char:
p
time:2, char:p
time:3, char:
m
time:4, char:m
time:5, char:
I'm not too sure why i is being incremented again, and why printf gets executed again. Perhaps I'm missing something.
Try
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
if (thing!='\n') {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}
#user2965071
char ch;
scanf("%c",&ch);
With such a snippet one reads any ASCII character from the stream including new line, return, tab, or escape. Thus, inside the loop I would test the symbol read with one of the ctype-functions.
Something like this:
#include <stdio.h>
#include <ctype.h>
int main(){
char thing;
int i=0;
while(1 == scanf("%c", &thing)){
if (isalnum(thing)) {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}
As for me, I think it's not a good idea to check scanf for returning EOF. I would rather check for the number of good read arguments.

How to scan initial spaces in C

I have a typical question it's not that how can I scan spaces using scanf but how to scan the initial spaces entered in a string
This is what I've done:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char a[10];
scanf("%d",&n);
scanf(" %[^\n]",a);
printf("%d",strlen(a));
return 0;
}
and when I run the program with following input:
aa bb//note there are two spaces before initial a
and the output is 6 but there are 8 characters i.e, 2 spaces followed by 2 a's followed by 2 spaces and then lastly 2 b's
I eve tried an own function.. but alas! the length is 6. Here's my function:
int len(char a[101])
{
int i;
for(i=0;a[i];i++);
return i;
}
What I think is that the initial 2 spaces are being ignored...or I might be wrong. It'd be great if someone could explain why the length of string is 6 and how can I make it 8 or accept all the 8 characters I mentioned above.
EDIT: this is my actual code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,N,j,k;
char **ans,s[101];
scanf("%d",&N);
ans=(char **)calloc(N,sizeof(char*));
for(j=0,i=0;i<N;i++)
{
scanf(" %[^\n]",s);
printf("%d",strlen(s));
ans[i]=(char*)calloc(strlen(s),sizeof(char));
for(k=0,j=((strlen(s)/2)-1);j>=0;j--,k++)
{
ans[i][k]=s[j];
}
for(j=strlen(s)-1;j>=strlen(s)/2;k++,j--)
{
ans[i][k]=s[j];
}
}
for(i=0;i<N;i++)
{
printf("%s\n",ans[i]);
}
scanf("%d",&i);
return 0;
}
OP code should work as posted.
OP comments true code is using scanf(" %[^\n]",a); which fully explains the problem: the space in the format is consuming leading white-space.
To address other issues with scanf(), see following.
fgets() is the right tool.
Yet if OP insists on scanf()
how can I scan spaces using scanf but how to scan the initial spaces entered in a string?
char buf[100];
// Scan up to 99 non\n characters and form a string in `buf`
switch (scanf("%99[^\n]", buf)) {
case 0: buf[0] = '\0'; break; // line begins with `'\n`
// May want to check if strlen(buf)==99 to detect a long line
case 1: break; // Success.
case EOF: buf[0] = '\0'; break; // stdin is closed.
}
fgetc(stdin); // throw away the \n still in stdin.
The issue i believe is that you need to be getting length from a Pointer to the array not the array itself.
Try this, this code worked for me.
int ArrayLength(char* stringArray)
{
return strlen(stringArray);
}

how to read a char value in C without going to next line

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
(WHY IS MY OUTPUT for the second printf and scanf not waiting for me to input a char before exiting the program?.....what i mean is u know where it says q=getchar();??? shouldnt it wait for to input a char before exiting the program? but for some reason the program just exits when it goes to the next line...
when pressing enter,a character '\n' is inputing.So your getchar() was used before you enter the second character.I think you want the code below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
int c;
while((c = getchar()) != '\n' && c != EOF && c != ' ') ;
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
You can also use a getch() instead of getchar() to avoid pressing enter key.
#include <stdio.h>
#include <conio.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getch();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getch();
printf("the char is: %c\n",q);
return 0;
}
When encountering invalid user inputs, use getchar() to read char, and other similar instances where there are undesired characters stuck at input stream(like in your case it was a newline) I define a constant named FLUSH
#define FLUSH while(getchar() != '\n')
to solve the problem. What this statement does is that it reads a character and then throws it away. Now if you try to place it after one of your getchars i.e.
p=getchar();
printf("the char is: %c\n",p);
FLUSH;
it will read the newline then stops because the condition within the while statement no longer holds.
Note: Using getchar() for prompts leaves a '\n' in the input stream you will find this troublesome once you make another prompt and have not eradicated that '\n'.

What's wrong with this simple C code?

#include <stdio.h>
int main()
{
int m,n; scanf("%d %d",&m,&n);
char ar[m][n];
char buf[n];
int a,b;
for(a=0;a<m;a++)
{
gets(buf);
for(b=0;b<n;b++) ar[a][b] = buf[b];
}
for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
return 0;
}
This code takes m lines as input from stdin, each line containing n characters, and prints all the lines to stdout. Simple as that. But there seems to be a memory leak, because the first time gets(buf) is encountered, its execution is skipped.
I tried it in C++ too, thinking the memory leak will disappear. Here is the code:
#include <cstdio>
using namespace std;
int main()
{
int m,n; scanf("%d %d",&m,&n);
char **ar = new char*[m];
char *buf = new char[n];
int a,b;
for(a=0;a<m;a++)
{
gets(buf);
ar[a] = new char[n];
for(b=0;b<n;b++) ar[a][b] = buf[b];
}
for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
return 0;
}
But it is behaving exactly the same.
Here is some sample input and output:
2 3
abc
def
output:
x��
abc
GDB doesn't seem to show anything up too. Please help..
It's not a "memory leak". The problem is that the first gets() call reads the newline from when you enter the two dimensions on the first line; it puts zero characters into the buffer, but you print 5, which is why you get a line of garbage.
Add a "\n" at the end of the scanf() format string so scanf() consumes the newline, and your program will work perfectly. Note that gets() is terribly unsafe; using fgets(buf, n, stdin) is much preferred.
In addition to missing '\n' in scanf() you should allocate more space for buf:
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m,n;
if(scanf("%d%d\n",&m,&n) != 2)
exit(EXIT_FAILURE);
char ar[m][n];
char buf[n+2]; // '\n\0'
int a,b;
for(a=0;a<m;a++)
{
if (!fgets(buf, n+2, stdin)) exit(EXIT_FAILURE);
for(b=0;b<n;b++) ar[a][b] = buf[b];
}
for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
return 0;
}
Output
abc
def

Resources