Satyam Garg
Satyam Garg

Reputation: 156

Not getting desired output in this simple program?

#include<stdio.h>
int main()
{
    int i;int n;
    scanf("%d",&n);
    char a[n];
    for(i=0;i<n;i++)
        scanf("%c",&a[i]);
    for(i=0;i<n;i++)
        printf("%c",a[i]);
    return 0;
}

//string is not duplicating exactly //scanf takes enter as a string but why?

Upvotes: 0

Views: 65

Answers (1)

jboockmann
jboockmann

Reputation: 1025

Your code actually behaves the way it should. Upon entering 3abc the program will print out abc. I guess what you aimed for instead was entering 3 then pressing enter and entering abc and upon pressing enter again abc should be printed out. In order to do so, you have to adjust the first scanf call.

#include<stdio.h>
int main()
{
    int i;int n;
    scanf("%d\n",&n); //add \n in order to read the "pressing enter"
        char a[n];
    for(i=0;i<n;i++)
        scanf("%c",&a[i]);
    for(i=0;i<n;i++)
        printf("%c",a[i]);
    return 0;
}

Upvotes: 3

Related Questions