jubjub
jubjub

Reputation: 1

Using scanf for char array in while loop

I am new to C programming. I was curious as to see how much I have learnt C. Therefore I thought of creating a program in which I could simply create a file and write in it. The name of the file, I thought, should be less that 100 chars. But it doesn't matter if it is a string or one word or a letter. I couldn't complete because I was stuck on fact that how to input a string for a file name(eg, Project work, New Doc1, etc)

So I wrote this;

int main()
{

    int a = 0;

    while(a != 5)
    {
        puts("Put a number: ");
        scanf("%i", &a);
        if(a == 1)
        {
            char name[30];
            printf("Put a name: ->>");
            for(int i = 0;i < 31 && name[i] != '\n';i++)
            {
                name[i] = getchar();

            }
            char ex[50] = ".txt";

            strcat(name,ex);
            printf("%s",name);

        }
    }

    return 0;
}

The problem is while inputting the name, it doesn't stop at the next (when I press enter) and some how it is not printing the right file name either.

Upvotes: 0

Views: 2601

Answers (2)

mike
mike

Reputation: 1

#include<stdio.h>
main()
{
    static char stop_char='y';
    char input=0;
    do{
        printf("please input a character\n");
        scanf("\n%c",&input);
    }while(input!=stop_char);
}

Upvotes: 0

iuridiniz
iuridiniz

Reputation: 2423

There's a lot of problems with you approach.

  1. It's not good to mix scanf with another input primitives, you must flush stdin from any remaining characters.
  2. Any string must end in '\0' in order to mark that string as complete. So you must reserve space to this character.
  3. When you concat you must obey the limit of the string.
  4. If you use printf, the string will be only displayed after flushing the stdout (when you put '\n' in the end of the string, flush is done)

Try this:

#include <stdio.h>
#include <string.h>   

int main()
{

    int a = 0;

    while(a != 5)
    {
        int ch;
        puts("Put a number: ");
        scanf("%d", &a);
        /* flush any remaining characters */
        while ((ch=getchar()) != EOF && ch != '\n'); /* issue 1 */
        if(a == 1)
        {
            int i = 0;
            char name[30];
            printf("Put a name: ->>");
            fflush(stdout); /* issue 4 */

            while ((ch=getchar()) != EOF && ch != '\n' && i < 25) /* issue 3 */
                name[i++] = ch;
            name[i] = '\0'; /* issue 2 */

            /* flush any remaining characters [if input > 25 chars] */
            if (ch != EOF && ch != '\n') while ((ch=getchar()) != EOF && ch != '\n');

            char ex[50] = ".txt";

            strcat(name,ex); /* issue 3 */
            printf("%s\n",name);

        }
    }

    return 0;
}

Also, consider use getline and atoi instead of getchar and scanf

Upvotes: 1

Related Questions