user5451270 February 2016

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();
}

Answers


hassan arafat February 2016

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


Magisch February 2016

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.

Post Status

Asked in February 2016
Viewed 2,946 times
Voted 13
Answered 2 times

Search




Leave an answer