how to check if cin command from console worked (linux)

Hello!

I have a program and that needs to read from a cin command in the terminal in linux.

What i do is that i start my program like this

./sort <input.txt

and now my program read the contents in given textfile and put it into a vector.

But if i for some reason forget to add the cin command and only write

./sort

the program crashes and i need to press ctrl+c in order to terminate the program. I was experimenting on a couple of solutions but i did not manage to solve it.

My function from reading from the text file and putting the contents in a vector can be seen here. One thing i tried as you can see is adding a if-statemnet with (input.fail()) but that did not work. I also tried cin.fail() which did not work either. Any other suggestions? Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 void filetoVEC(vector<Sortering>& vecSortering)
{
  int tempsiffror;
  string tempbokstaver;
  string tempromerska;
  istream& input = cin;

  if (!input.fail())
  {
    while (!input.eof())
    {
      if (input.good())
      {
        while (input >> tempsiffror >> tempbokstaver >> tempromerska)
        {
	   vecSortering.push_back(Sortering(tempsiffror, tempbokstaver, tempromerska));
        }
      }
      else
      {
        cout << "Filen öppnades ej korrekt" << endl;
      }
    }
  }
  else
  {
    cout << "Ingen textfil angiven." << endl;
  }
}
Last edited on
If you mean that you are giving command line arguments, then you can just check the value of argc. If its less than 2, then the file was not passed to the program, and you can then terminate the program.
the program crashes and i need to press ctrl+c in order to terminate the program.

No, it doesn't crash. It sits there patiently waiting for some input. You can signal end of input with ctrl-d (or ctrl-z on windows).
http://stackoverflow.com/questions/28216437/end-of-file-in-stdin

The previous suggestion to use command-line argument argv[1] may be more suitable, but you will need to change your program to handle that, rather than using the standard input (cin).
Oh okay, never thought of doing it like that.

Is it possible to do something like:

1
2
3
4
5
6
7
8
if (!argc < 2) 
{
  //Random code
}
else
{
  exit();
}



NINJAEDIT: Did not seee Chervils reply.
So i have to rewrite the function to do it? I am not sure if i have time for that, this is a assignment due tomorrow and i finished but this problem is annoying me so much i wanted to solve before i turned my program in.

If there is no other way the rewriting the function i think it will have to do like this.
Last edited on
I manage to get some help from a teacher and added C library with isatty function and know when i typ only ./sort i get the error message.

1
2
3
4
5
6
7
#include <unistd.h>

if (isatty(STDIN_FILENO == 1))
{
   cout << "Random error code....." << endl; 
   exit (0);
}
Last edited on
Topic archived. No new replies allowed.