user1386966
user1386966

Reputation: 3392

how to loop user input and copy it to file until "exit" string in entered using C?

I want to write some small program that is getting strings from the user(using console) when max input is 100 characters , and when user pressed enter - it will copy the input to some file. I want to exit the loop when user enters the string "exit"

for example : "hi how are you?" " bla bla" "exit" I just don't get how to make it work - should I use scanf? getchar? fgets?

char* buf ;
int i;


 buf = (char*)calloc(100, sizeof(char));
 while(1) 
  {
     fgets(s, sizeof(s), stdin);
     if (strcmp(s , "exit") == 0)
       break;
     else
   ...write to file...
   }

do I need manually put "\0" ?

thanks!

Upvotes: 1

Views: 3576

Answers (3)

autistic
autistic

Reputation: 15642

should I use scanf? getchar? fgets?

Any of the above, but your while loop should translate to: while input is read, and the input isn't "exit". Your while loop currently translates to: while the world doesn't end.

I suggest something like:

while (fgets(s, sizeof s, stdin) == s && strcmp(s, "exit\n") != 0) {
    /* ... */
}

do I need manually put "\0" ?

No; careful selection of tools allows you to operate upon strings produced by the standard I/O library (in the case of the fgets/strcmp code above) using the standard string library, or upon non-strings by other more complex means.


PS. There is no need to cast malloc, and sizeof (char) is always one in C.

Upvotes: 2

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

For your question, fgets() automatically appends a \0.

From C++ Reference:

A terminating null character is automatically appended after the characters copied to str.

Do note that fgets() stops reading at the press of Enter and appends a \n too, but, from your question, I gather that this might be favourable to you.

For the differences between fgets() and scanf(), a good discussion can be found here..

Upvotes: 1

user529758
user529758

Reputation:

fgets() is fine, but in some implementations, it puts the trailing newline (\n) to the end of the line. You have to remove it in order the comparison to work, or prepare your comparison to accept both "exit" and "exit\n":

if (strcmp(s , "exit") == 0 || strcmp(s , "exit\n") == 0)
   break;

or

fgets(s, sizeof(s), stdin);
char *p = strchr(s, '\n');
if (p) *p = 0;

if (strcmp(s , "exit") == 0)
    break;

Sidenote: unless you intend to return the string to a caller function, there's no need for using calloc() at all. Use an automatic array instead:

char s[0x100]; // or whatever

Upvotes: 2

Related Questions