0

I'm writing a function that reads line by line from cin and returns when it sees ; character.

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

using namespace std;

int read_cmd(char *cmd)
{
    cout << "Please enter a string: \n";
    cmd[0]='\0';

    while(1){
        char currentLine[10000];
        currentLine[0]='\0';
        cin.getline(currentLine,10000);
        if (strcmp(currentLine,";")==0){
            break;
        }
        strcat(cmd, "\n");
        strcat(cmd, currentLine);
    }
    return 0;
}

int main(){
    char cmd[1000];
    while (1){
        read_cmd(cmd);
        cout<< cmd << endl;
    }
}

I then tested it using text fed from another file via pipe. ./read_cmd < test_file

contents of test_file:

line 1
line 2
;

This outputs results just fine, however it gives me a segmentation fault at the end. Is there a way for cin to check if it's coming across an EOF and terminates?

user3386109
  • 34,287
  • 7
  • 49
  • 68
zzxx53
  • 413
  • 3
  • 12

2 Answers2

0

I would highly suggest the use of the string object for something like this, that way you're not wasting space, as well as ensuring that you have enouch space. You can also do it without a loop.

string currentLine;
getline(cin, currentLine, ';');

Now, if you need to get just the last line with has the semi-colon, a loop is necessary, but still you can do it at little more easily.

string currentLine;
while(getline(cin, currentLine)){
    if(currentLine.find(";") != string::npos){
        break;
    }
}

Use strings to pass things around as well. There's always the .clear() method as well that any string has for easy emptying.

string getline
string Object

David
  • 4,744
  • 5
  • 33
  • 64
0

To detect the EOF you should use something like:

while (cin.good() && !cin.eof())
{
    // Read the file
}

See the documentation for cin, in particular the good() (for error checking) and eof() member functions.

In particular this example might be helpful.

nonsensickle
  • 4,438
  • 2
  • 34
  • 61