0

Writing a simple code that's suppose to scan an integer and a character and then write them out. my input is 1a and the output should be 1a but i'm getting 0 on the integer spot. have a pretty basic understanding of c so may have missed something that's pretty obvious thanks in advance.

#include <stdio.h> 
int main()
 { 
   int a; 
   char b; 
   scanf("%d", &a); 
   scanf(" %s", &b); 
   printf("%d", a); 
   printf("%s", &b); 
 }
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
Noncode101
  • 13
  • 1
  • 2
    Edit the question to include your code. Don't post it as a comment. – dbush Oct 23 '18 at 12:58
  • 3
    Please read [the help pages](http://stackoverflow.com/help), especially ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) and [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Oct 23 '18 at 12:59

4 Answers4

0

b is a char, %s is for string input so adds trailing 0 after b and you can get a crash. Use %c to input char.

0

You basically want this:

#include <stdio.h> 

int main()
{
  int a;
  char b[100];     // array of 100 chars

  scanf("%d", &a);
  scanf("%s", b);

  printf("%d", a);
  printf("%s", b);
}

To fully understand this, you need to read the chapters dealing with scanf and the one dealing with strings in your C text book.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

b is a character so replace %s with %c, moreover

  1. scanf() takes & before the variable as it want to store the variable refering to that address.

2.printf() Just outputs the value to the console present in that varaible. Thereby no need to use & inside it

CORRECTED CODE:

    #include <stdio.h> 
    int main()
    { 
     int a; 
     char b; 
     scanf("%d", &a); 
     scanf(" %c", &b); 
     printf("%d", a); 
     printf("%c", b); 
     }
0

you can try it:

#include <stdio.h>
int main()
 {
  int a;
  char b;
  scanf("%d", &a);
  scanf(" %c", &b);
  printf("%d", a);
  printf("%c", b);
 } 
S. Hesam
  • 5,266
  • 3
  • 37
  • 59