-3

I have got a stream of characters as input without any whitespaces, and I have to store them in a character array using scanf().

#include <stdio.h>
#include <iostream>

int main() {   
    int n,q,l,r,k;
    scanf("%d",&n);
    char A[n];
    scanf("%d",&q);

    for(int i=0; i<n; i++) {
        scanf("%c",&A[i]);
    }
    for(int i=0; i<n; i++) {
        printf("%c",A[i]);
    }
    return 0;
}

The above loop does not work.

Rohan Sharma
  • 405
  • 1
  • 3
  • 11

1 Answers1

0

The loop will work only if you have declare (and possibly initialized) n, otherwise the compile will complain that n has not been declared.

Then, when the program run you are asked to insert n characters. Note that every key you press will be interpreted as a char, so that, if n=10:

1 2 3 4 5

are 10 character because you have entered 5 numbers, 4 spaces and a new line character '\n' to give the input to your program.

So, if you need to populate your array with 10 numbers, say from 0 to 9, you need to write:

0123456789

and then press enter. Note that in this way you provide 11 characters, 10 numbers and the new line but only the first 10 are read, because of the bound of your loop.

Note: this program can only accept one-digit numbers as long as you are using char

Advise:since you are using C++, do not use the C I/O-library stdio.h but the C++ one: iostream

Neb
  • 2,270
  • 1
  • 12
  • 22
  • Input is of the form of letters(a-z). n ,has been initialised earlier in the code. I have included both iostream and stdio.h directories. I am taking input from an online compiler, when I try to input "ball", and try to print A[0],A[1],A[2] individually output is (endl), b, a. Working perfectly with cin. – Rohan Sharma Sep 16 '17 at 09:37
  • @RohanSharma See [this](https://stackoverflow.com/questions/20306659/the-program-doesnt-stop-on-scanfc-ch-line-why) – BLUEPIXY Sep 16 '17 at 09:48
  • it was better you edited your post instead of writing here..delete the '&' from your printf() – Neb Sep 16 '17 at 09:49