954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Small problem with C

Hi there folks,

I got some minor problem with this code:

#include <stdio.h>
#include <stdlib.h>

int main(){

    char option, factor;

    printf("Choose your operator: \"+\" ; \"-\" ; \"*\" ; \"/\" \n>\t");
    scanf(" %c", &option);
    printf("You chose : %c \nChoose your factor:\n>\t", option);
    scanf("%d", &factor);
    printf("You chose : %i\n",factor); 
    printf(" %c", option);
    
    if(option=='+'){
        printf("It's WORKING!");
        system("pause");
    }

    return 0;
}


and it doesn't work. Program skips "if()" as if it wasn't there and continues with "return 0;". On the other hand if I remove "scanf("%d", &factor);" it works prefectly fine!

Can anyone tell me why?

regards

Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

Give this a read. There can be problems with stray '\n' (newline) characters in the buffer. The code snippet there shows how to flush them out (and even offers the use of getchar as a more effective method in this case.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

Scanf isn't clearing the input buffer of the new line character..

i.e. When you enter an operator you enter the operator character plus you hit the return key...So two characters are placed in the input buffer, the one you want plus the newline character and scanf only picks up the operator character leaving the newline in the buffer.

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 
#include <stdio.h>
#include <stdlib.h>

int main(){

    char option, factor;

    printf("Choose your operator: \"+\" ; \"-\" ; \"*\" ; \"/\" \n>\t");
    scanf(" %c", &option);
    printf("You chose : %c \nChoose your factor:\n>\t", option);
    scanf("%d", &factor);
    printf("You chose : %i\n",factor); 
    printf(" %c", option);
    
    if(option=='+'){
        printf("It's WORKING!");
        system("pause");
    }

    return 0;
}

It looks like the problem would be that factor is of type char , but when you do the scanf(...) , you tell to input aninteger (i.e. "%d") instead of char . So, scanf() happily accepts anything that fits into an int , and because an int consumes more memory than a char , you will end up overwriting stack memory - and that changes the value of option .

You might add; printf("option is now [%c]", option); there, so that you see that the value has changed.

So you might remedy this by ..

int main(){

  char option;
  // 'factor' changed to int instead of char ...
  int factor;
  // .. and the rest of the code as is ...


I hope that made some sense. At any rate, you don't want to use mismatched/erroneousformat strings with any of the scanf/printf -family functions.

PS. hint: GCC is quite good at pointing out mismatched format strings.

mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
 

Thanks a MIL mitrmkar!!! I completely forgot that original I had factor as char . So I changed it to int and it works like a charm! scanf() is flushing <newline> as %d is skipping newline anyway - that's what i learned yesterday. It's scanf("%c",&x) with c, where the problem exists, and to prevent that a space is required, scanf(" %c",&x) , that's what I have learned over the weekend anyway.

Thanks all of you guys for help!
Cheers

Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

Oops. I was mistaken....

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Another problem lads:

#include <stdio.h>
#include <stdlib.h>

int main(){
    
    int factor, o, copy[10], i;
    char option, input[20], output[20], getnumber[10], a[20];
    FILE *source, *target;
    
    do{

        printf("Name input file:\t");
        scanf("%s", &input);
        source=fopen(input, "r");
        if(source==NULL)
            printf("\nCannot access input file. Try again.\n");
    }while(source==NULL);
   
    printf("Name output file:\t");
    scanf("%s", &output);
    target=fopen(output, "w");
    
    printf("Choose your operator: \"+\" ; \"-\" ; \"*\" ; \"/\" \n>\t");
    scanf(" %c", &option);
    printf("You chose : %c \nChoose your factor:\n>\t", option);
    scanf("%d", &factor);
    printf("You chose : %i\n",factor); 
    printf(" %c", option);

    if(option=='+'){
        printf("\nLet's Add!!!\n");
        system("cls");
        do{ 
            o=0;
            do{                                                         //do that causes the problem
                getnumber[o]=fgetc(source);                
                
                if(getnumber[o]==' '){
                     /*               some function        */
                }

                o++;
                printf("\n\n%d",o-1);                                   //used to find out the number of extra useless lines before terminating i.e. 316 lines
            }while(getnumber[o]!=' ');                                  //this while goes with do

        }while(getnumber[o-1]!=EOF);

    }    
    fclose(source);
    fclose(target);
    system("pause");
}


Now as in comments I pointed out a do{} is causeing me some problems. The function works perfectly untill the program gets to the end of the string in the input file, that it repeats getnumber[o]=fgetc(source); only, and when it gets to o =315 that it terminates.

On the other hand if i remove the do{ and }while(getnumber[o]!=' '); , the program works fine! It's just that I need this do loop there.

Please any ideas guys?

Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 
On the other hand if i remove the do{ and }while(getnumber[o]!=' '); , the program works fine! It's just that I need this do loop there.


This is another one of those "what the heck" problems. If you remove the do-while and the code works fine, then you don'tneed the do-while .

Kinda like if you know how to get to your friend's house, you really don't need the GPS.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

But I do need it to compute the number, do operation on it. The program is not finished you see. And plus I want to know why it doesn't work.

Or should I resign from the loop and find alternative way?

Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

Ok I found the error

Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

Nope it is not working....

Help GUYS!!!

Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

Please post up your most recent code. I know you've made some changes, and I'm late joining this thread.

Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
 

code is the same:

#include <stdio.h>
#include <stdlib.h>

int main(){
    
    int factor, o, copy[10], i;
    char option, input[20], output[20], getnumber[10], a[20];
    FILE *source, *target;
    
    do{

        printf("Name input file:\t");
        scanf("%s", &input);
        source=fopen(input, "r");
        if(source==NULL)
            printf("\nCannot access input file. Try again.\n");
    }while(source==NULL);
   
    printf("Name output file:\t");
    scanf("%s", &output);
    target=fopen(output, "w");
    
    printf("Choose your operator: \"+\" ; \"-\" ; \"*\" ; \"/\" \n>\t");
    scanf(" %c", &option);
    printf("You chose : %c \nChoose your factor:\n>\t", option);
    scanf("%d", &factor);
    printf("You chose : %i\n",factor); 
    printf(" %c", option);

    if(option=='+'){
        printf("\nLet's Add!!!\n");
        system("cls");
        do{ 
            o=0;
            do{                                                         //do that causes the problem
                getnumber[o]=fgetc(source);                
                
                if(getnumber[o]==' '){
                     /*               some function        */
                }

                o++;
                printf("\n\n%d",o-1);                                   //used to find out the number of extra useless lines before terminating i.e. 316 lines
            }while(getnumber[o]!=' ');                                  //this while goes with do

        }while(getnumber[o-1]!=EOF);

    }    
    fclose(source);
    fclose(target);
    system("pause");
Agello
Newbie Poster
7 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: