简体   繁体   中英

Upon running the i get a pop up windows screen saying “prg.exe has stopped working.”

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;
int main()
{
  char str[100];
  cout << "Enter a string : ";
  gets(str);
  cout << "The words containing y in their last place are : ";
  cout << "\n";
  for(int i = 0; str[i] != '\0'; i++)
  {
    int j = i + 1;
    if((str[i] == 'y') && (str[j] == ' '))
    {
      int k;
      cout << 134;
      char stress[50];
      int m = 0;
      k = i;
      for(; (str[k] != ' ') || (k != 0); k--, m++)
      {
        stress[m] = str[k];
      }
      stress[m] = '\0';
      int g;
      for(g = 0; stress[g] != '\0'; g++)
        ;
      char strain[g];
      for(int n = 0, q = k - 1; q >= 0; n++, q--)
      {
        strain[n] = stress[q];
      }
      strain[g] = '\0';
      for(int p = 0; p < g; p++)
      {
        cout << strain[p];
      }

      cout << "\n";
      cout << 1;
    }
    cout << 12;
  }

  return 0;
}

This c++ program is to display the word containing 'y' as its last letter. I used cout<<12 cout<<1 etc.. to know which part of program is working. Dont get confused by seeing strain and stress. They are just strings. I am using codeblocks in windows 7

Upon running the program i get a pop up windows screen saying "prg.exe has stopped working." Please someone tell me why this error is occuring. I use codeblocks I will be really grateful.

You might have errors because of using gets() function, because when you are using gets() you need to know the amount of characters you will get. It was officialy removed by 2011 standart, but almost every C implementation uses it. So to avoid that dangerous function you can use:

  • getline() , which is very easy to use - like that:

    getline(cin,str);

  • fgets() , it is used like gets , but you need to mention how many characters you will read:

    fgets(str, num_of_chars, cin);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM