0

i am a starter and i have written a code:

#include<stdio.h>
char c;
char a[100]={0};
int i;

int main(void)
{   
  while(1)
  {
    i=0;
    while(1){
      if((c=getchar())!='\n'){
        a[i]=c;
        i++;
      } else {
        break;
      }
    }
    printf("%s\n",a); 
  }
  return 0;
}

and now i have idea that i want to add a break statement that when i type q, the program will break. so my new program is:

#include<stdio.h>
char c;
char a[100]={0};
int i;

int main(void)
{   
  while(1)
  {
    i=0;
    while(1){
      if((c=getchar())!='\n'){
        a[i]=c;
        i++;
      } else {
        break;
      }
    }
    printf("%s\n",a);
    if(getchar()=='q')break;       /*i added this*/
  }
  return 0;
}

i know because the getchar() conflict the code is not correct, how can i do, to add the type q break command. thanks a lot.

Soren
  • 14,402
  • 4
  • 41
  • 67
Kevin
  • 59
  • 6
  • start by learning how to avoid using `global variables` when not need – Seek Addo Feb 20 '17 at 02:07
  • @SeekAddo What do you mean *global*? Those variables have internal linkage, so they're not visible to other modules... Would you mind showing me where within [the C standard](http://www.iso-9899.info/n1570.html) I can find more information about *global variables*? I'd like to learn how to declare and use them... – autistic Feb 20 '17 at 02:50
  • @Seb Global variables can be accessed from anywhere in the application. They can be deemed bad practice by some, as the variables can be modified by another function. `char c; ` `char a[100]={0};` `int i;` were all defined outside the `main`. Any function within this application can access them for which is a bad practice – Seek Addo Feb 20 '17 at 02:56
  • @SeekAddo Can those globals be accessed from *anywhere* within the application? How about prior to their declaration, e.g. `char return_c(void) { return c; }` followed immediately by `char c;`... Is that possible? Can those globals be accessed from other translation units? Do you understand what a translation unit is? – autistic Feb 20 '17 at 03:03
  • You said it yourself, *globals* are accessible *anywhere*... but you can see from my code, `c` isn't accessible *anywhere* despite being declared outside of functions, because it isn't accessible to functions declared *before* it! So none of these variables are globals, and C doesn't have globals. The other example is translation units; once you learn about using the linker, you'll find that none of these variables are accessible to modules linked using the linker... Further proof that C has no *global variables*. **But the ultimate proof is in the C standard, which I linked to earlier**... – autistic Feb 20 '17 at 03:11
  • @SeekAddo More importantly, you need to ask yourself in the future, *is this comment actually useful for this question*? The answer, as a rule of thumb, is: *most stylistic comments are useless*. – autistic Feb 20 '17 at 03:12

3 Answers3

1

Unlikely to be what you actually want, but at least this will work

#include<stdio.h>

int main(void)
{
  char a[100]={0};
  int i = 0;
  do {
    int c = getchar();
    switch (c) {
       case EOF:
           /*EOF*/
           return -1;
       case '\n':
           a[i] = 0;
           printf("%s\n",a);
           i= 0;
           break;
       default:
           a[i++] =c;
           break;
  } while (c != 'q' || i > 1);
  return 0;
}
Soren
  • 14,402
  • 4
  • 41
  • 67
  • Are you sure `EOF` is guaranteed to be -1? Why inject the magic number, rather than just writing `EOF`? – autistic Feb 20 '17 at 02:35
  • I used -1 to illustrate that the `c` could not be of type char, but sure I could have written a longer explanation -- and yes, while EOF usually is -1, then [it is only guaranteed to be a negative number](http://stackoverflow.com/a/4706217/668501) – Soren Feb 20 '17 at 02:47
  • Also, contrary to your introduction ("Unlikely to be what you actually want"), I think this *is* likely to be what the OP asked for... so you've got +1 from me for that, and for your quasi-correct `getchar` error handling. – autistic Feb 20 '17 at 02:53
1

i am a starter and i have written a code

Uh oh! Here goes... Firstly, the odds of successfully learning the portable, standard-compliant C programming language are overwhelmingly low for anyone who tries to learn by unguided trial and error. There's a really nice book you can use as a guide, but you need to read it AND do the exercises as you stumble across them. That's K&R2E, if you're interested.


Anything resembling char c; c = getchar(); is erroneous because the narrowing conversion from int (which getchar returns) to char discards error handling information.

Any character values returned by getchar will be as unsigned char values converted to an int, so it'd technically be more correct (though still incorrect) to use that type.

Error values are returned as a negative integer such as EOF, not to be confused with character values, which is exactly what your code does wrong by discarding the error information.

getchar returns int, so store the value into an int, then test for errors, then, if you must, convert it down to an unsigned char.


and now i have idea that i want to add a break statement that when i type q, the program will break.

Following on from the previous discussion, such a requirement is superfluous, nonetheless easy to incorporate if you're handling errors correctly. Just insert an extra test to match against q into the error handling, and presto!

Nonetheless, the error handling most likely already solves this problem, as most OSes have a mechanism to close stdin, which would cause getchar to return EOF, thus triggering the error handling clause. This is typically achieved by pressing CTRL+d in Linux, or CTRL+z in Windows, for example.


In conclusion, providing you aren't already reading one, it seems a nice book about C isn't all that'd benefit you; a nice book about console scripting for your favourite Unix-like OS would also be highly beneficial.

autistic
  • 1
  • 3
  • 35
  • 80
0

Try this code:

#include <stdio.h>
#include <stdlib.h>

#define q 113  --> These values are coming from ASCII table.
#define Q 81 

int main(void)
{
    char ch = 0;
    do
    {
        ch = getchar();
        switch(ch)
        {
            case q:
                // your logic goes here
                exit(0);
            case Q:
                // your logic goes here
                exit(0);
            /* more cases can come here */
        }
    }
    while(1);
}
Milind Deore
  • 2,887
  • 5
  • 25
  • 40
  • Thanks Soren, fixed. Also instead of `exit()`, we can still use `break` if there is some exit_flag or condition outside switch is required. – Milind Deore Feb 20 '17 at 02:32