Kyle Hobbs
Kyle Hobbs

Reputation: 457

Get a string, denoted by quotes, out of a file with ifstream and get()

I'm trying to parse a file for strings, which are denoted by double quotes in the file. Once I find a string, I'll store it in a variable and do what I want with it (for the purposes of this question lets just say print it). My problem is I can't figure out how to get these strings, particularly if they have spaces. Here is an example of the input:

100 20
"String"
"With Space"
'c' ' '

Note: The only strings in this input are String and With Space. All of the other data should be ultimately ignored. Here is my code which is not printing anything at all.

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        ifstream input;
        input.open(argv[i]);

        char c;
        while (input.get(c)) {
            if (c == '"') {
                string s;
                while (c != '"') {
                    char letter;
                    input.get(letter);
                    s += letter;
                }
                cout << s << "\n";
            }       
        }
    }
}

Note: I've included iostream and fstream. And I'm using namespace std.

Upvotes: 2

Views: 128

Answers (1)

Sid S
Sid S

Reputation: 6125

In this fragment:

    if (c == '"') {
        string s;
        while (c != '"') {

The while loop can never be entered.

You need to read the next character before testing for end of quoted string.

So something like this:

    if (c == '"') {
        string s;
        while (input.get(c) && c != '"') {
            s += c;
        }
        cout << s << "\n";
    }       

Upvotes: 1

Related Questions