2015-01-08 3 views
0

Я продолжаю получать ошибку времени выполнения 3 - переменная 'gl' используется без инициализации. Код соответствует и работает нормально, пока он не будет использовать «gl» в конце кода.C ошибка времени выполнения # 3

gl предназначен для обозначения одного символа.

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 
#include<varargs.h> 
#include<time.h> 
#define false 0 
#define true 1   

/*This function works out if the number giver is a whole number, and it's greater than 3 chraters long*/ 
int numeric(char *string) 
{ 
    unsigned int i; 
    int valid = true; 

    for (i=0;i<strlen(string); i++) 
    { 
     { 
      if (string[i] < '0' || string[i] > '9') /*Check to make sure that only numeric chraters have been entered*/ 
       valid=false; 
     } 
    } 

    return valid; 
} 


int main(int argc, char *argv[]) 
{ 
    char gl,c;        /*gl number of guesses, Most recently read character*/ 
    int t, n, gc, i, e, lc = 0, wordcount; /* Lc is the number of astericks left,Number of woods in a file*/ 
    short in_word;       /*Ture or False variable*/ 
    char guessword[50];     /*This is the word that get's copied from the file*/ 
    char selectword[50];     /*Is copied from guessword, need change it's size to that of lc, and to then print *'s in place of charaters*/ 
    int chars_in_word = 0; 
    FILE *file; 

    wordcount=0; 

    if (argc==3) 
    { 
     printf("The arguments supplied is %s\n",argv[1]); 
    } 
    else if (argc>3) 
    { 
     printf("too many aguments.\n"); 
     return 1; 
    } 
    else if (argc<3) 
    { 
     printf("too few arguments.\n"); 
     return 2; 
    } 

    if (! numeric(argv[2])) /*Checking that string with the numeric function*/ 
    { 
     printf("Invalid input, seconed arugment is not an int"); 
     return 3; /*Exiting programing if the funcation numeric turns false*/ 
    } 
    else 
    { 
     printf("Arguments ok.\n"); 
     gc=atoi(argv[2]); 
    } 

    file = fopen(argv[1], "r");  /* Check file wordtext.text can be opened */ 

    if (file==0) 
    { 
     printf("Error opening file.\n"); 
     perror(""); 
     return 4; 
    } 
    else 
    { 
     printf("File opening ok.\n"); 
    } 

    in_word=false; 

    while ((c=fgetc(file))!=EOF) /* word count*/ 
    { 
     if(c!=' ' && c!= '.' && c!= ',' && c!='\t'&& c!= '\n') 
     { 
      if (! in_word) 
      { 
       wordcount++; 
       in_word=true; 
      } 
     } 
     else 
     { 
      in_word=false; 
     } 
    } 

    if ((fclose(file))==EOF) 
    { 
     printf("%s: Error closing file '%s'\n", argv[2]); 
     perror(""); 
     return 5; 
    } 

    printf("%d\n",wordcount); 

    srand(time(NULL));  /*Random number Generator*/ 
    for (t=1;t<=150;t++) 
    { 
     n=(rand() % wordcount + 1); 
    } 
    printf("%d\n", n); 
    i=0; 

    file = fopen(argv[1], "r"); /* I've not worked out how to skip to the selected word (wordcount)*/ 

    while ((c = fgetc(file)) != EOF) 
    { 
     if (c != ' ' && c != '\n' && c != '.') 
     { 
      guessword[chars_in_word] = c; 
      chars_in_word++; 
     } 
     else 
     { 
      guessword[chars_in_word] = '\0'; 
      chars_in_word=0; 
      i++; 
      if (i == n) 
      { 
       fclose(file); 
       break; 
      } 
     } 
    } 

    printf("Word guess: %s\n",guessword); /*change this into an array*/ 

    e=0; 

    for (e = 0; e<guessword[e]; e++) { 
     if (guessword!="\0") 
     {       
      printf("*"); 
      lc++; 
     } 
    } 

    printf("\n%d\n",lc); 
    printf("Number of guesses left %d\n",gc); 
    printf("Enter guess: "); 
    scanf("%s", gl); 
    printf("%s",gl); 

    /*While number of guesses != 0*/ 
    /*count = length of guessword*/ 
    /*Enter guess*/ 
    /*If guess = char*/ 
    /*print that char, count (lc) - 1*/ 
    /*If count = 0*/ 
    /*Well done*/ 
    /*if number of guesses = 0*/ 
    /*Hard luck*/ 
    return 0; 
} 

Я искал в Интернете, но только нашел материал, связанный с ints и reals. у кого есть идеи. извините, если это кажется очень простым.

+0

Рассмотрим inluding '' вместо определения '' true' и false' себя. Кроме того, вы можете заменить '' на ''. – Deduplicator

+0

Какие ошибки вы получаете? – Scriptable

ответ

1

gl заявлен как char в вашей программе, но s для преобразования требуется char *. Обязательно передайте указатель на первый элемент объекта массива char.

scanf("%s", gl); 
printf("%s",gl); 

Прежде чем продолжить, включите все предупреждения в свой компилятор и исправьте их все.

1

gl - char, а не строка. Передача не указателя на scanf() никогда не будет устанавливать значение для этой переменной. Он также завершится с ошибкой как параметр %s до printf().

переобъявить gl как:

char gl[50]; 
Смежные вопросы