user5451270
user5451270

Reputation: 79

Program gets terminated abruptly in Visual C++

Whwenever I try to execute this block of code it abruptly shuts down if I dont use the getch() function. Moreover I have tried different combinations of accepting and printing the string like gets() and puts() etc. My question is what causes this error and how can i remove this error?

void main()
{
  char str[100];
  printf("Enter your string\n");
  fgets(str,100,stdin);
  printf("%s",str);
  getch();
}

Upvotes: 1

Views: 179

Answers (2)

hassan arafat
hassan arafat

Reputation: 667

This is the expected behaviour when you run and attach a debugger. Try running with ctrl+f5.

Upvotes: 0

Magisch
Magisch

Reputation: 7352

void main()
{
  char str[100];
  printf("Enter your string\n");
  fgets(str,100,stdin);
  printf("%s",str);
  getch();
}

You have many problems for a small program.

  1. you are using getch(); This requires you to #include <conio.h>
  2. You are using printf() family functions. This requires you to #include <stdio.h>
  3. The function prototype for main() has to be int main(void) in your case

In conclusion, this would be the fixed code:

#include <stdio.h>
#include <conio.h>
int main(void)
{
  char str[100];
  printf("Enter your string\n");
  fgets(str,100,stdin);
  printf("%s",str);
  getch();
  return 0;
}

run it from the cmd.exe command line window.

The reason it shuts down is because after completing everything in the program, the program automatically terminates. Getch() just makes the system wait for another input.

Upvotes: 1

Related Questions