0

I am very confused to why my program isn't running well. I am connected to a server through my windows PC using PuTTY. It always works fine but something weird is going on I believe. Here's the code for identify.c :

#include <stdio.h>
#include <ctype.h>

int main()
{
    while(1)
    {
        char word[256];
        int i;
        int validity = 1;

        scanf("%s", word);

        for(i=0; word[i]!='\0'; i++)
        {
            if(i == 0)
            {
                /* First character should only be underscore or a letter */
                if(word[i]!= '_' && !isalpha(word[i]))
                {
                    validity = 0;
                    break;
                }

            }
            else
            {
                /* Rest can be Alpha-numerics or underscore */
                if(word[i]!= '_' && !isalnum(word[i]))
                {
                    validity = 0;
                    break;
                }
            }

        }

        if(validity)
            printf("valid\n");
        else
            printf("invalid\n");
    }

    return 0;
}

Here's the input file for testing if a name is a possible identifier name or not. identitytest.txt :

name

name2

2name

_name

__name

na_me

@name

na-me

I then upload both files to my server using FileZilla.

I then do the following command to make identify.c executable:

gcc identify.c -o identify

Executable has been created. Then I run the following command:

identify <identifytest.txt >output.txt

The created output.txt is then empty.

Any ideas why? I've been going crazy over this for the past 2 days not figuring out what is happening.

abelenky
  • 63,815
  • 23
  • 109
  • 159

2 Answers2

1

You have to break the infinite loop when std input closed:

if (scanf("%s", word) == EOF) break;

also you can flush standard output to force writing the results to the output file:

fflush(stdout);
simon
  • 1,210
  • 12
  • 26
0

Your program does not have an exit condition. I only added one line

if(i == 0)
    {
    if (word[i] == '!') return 0;       // <--- added this line
    ...

Then the command (similar to yours)

test <test.txt >output.txt

writes the expected results to output.txt after the line "!" is read.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56