2

so I wanted to write a simple program and to start with I made this. It works fine, but after it finishes it crashes (a window pops up with "the program has stopped working") and returns a big number instead of just returning 0.

Can you tell me what is wrong?

I use Code:Blocks (GNU GCC Compiler).

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cctype>

using namespace std;

int main()
{
ifstream ifs;
ofstream ofs;

char input[80];
char output[80];
char text[6];

cout<<"Input file name"<<endl;
cin>>input;
ifs.open(input, ios::in);

if(!ifs)
{
    cout<<"Wrong file name!"<<endl;
    system("pause");
    return 0;
}

cout<<"Output file name"<<endl;
cin>>output;
ofs.open(output, ios::out);

    ifs>>text;

    if(strcmp("$GPGGA",text))
    {
        cout<<"DATA FOUND"<<endl;
    }

system("pause");
return 0;
}
Matt
  • 194
  • 1
  • 1
  • 14
  • 1
    https://stackoverflow.com/q/1107705/436282 – Andrew Dec 15 '15 at 22:01
  • 5
    My crystal ball thinks that the first word in your input file is more than five characters long. (Note that `"$GPGGA"` is an array of seven `char`s.) – molbdnilo Dec 15 '15 at 22:02
  • This is `system("pause")` which is to blame, but take care of your use of `strcmp(left, right)`: it returns 0 when `left` and `right` match. By the way, my system warns me of the cause: "*sh: 1: pause: not found*". – YSC Dec 15 '15 at 22:04
  • 2
    `std::string` makes your life a lot easier. For example, you're using `strcmp` backwards and the crash is likely an out of bounds array access. – chris Dec 15 '15 at 22:04
  • Please include which line it crashed on as well as the stack trace in the question. – MrEricSir Dec 15 '15 at 22:07
  • 1
    Why the awkward mix between C++ and C style IO / string handling in the first place? – Baum mit Augen Dec 15 '15 at 22:08
  • 1
    @YSC `system("pause")`, although bad style, is not to blame. The OP is obviously using Windows, while you're using some POSIX system, where "pause" doesn't exist. – PC Luddite Dec 15 '15 at 22:57
  • Thank you mlobdnilo, that was the answer to my problem :) I thought that it will only get 6 characters from my document. – Matt Dec 15 '15 at 23:01

0 Answers0