0

I have a .txt file:

Fruit name:
"Banana - yellow"
"Apple - red"
"Grape - purple"

I am trying to extract each line, and make it so that any line that begins with " outputs the the first word in that line.

I currently have my code set up as the following:

char text_line[1000];
while(cin.good()){
    std::cin.getline(text_line,1000);
    if(text_line[0] == '"')
    {
        string instr(text_line);

        std::string tok;

        std::stringstream ss(instr);

        while(std::getline(ss, tok, ' '))
        {
              cout<<"This is the first word: "<<tok<<endl;
        }

    }
}

My problem is that the only word that outputs is "Banana", which shows me that the if-statement in my while-loop is only being executed for that one line. Is there any way to overcome this? Thank you in advance!

skypjack
  • 45,296
  • 16
  • 80
  • 161
user5620123
  • 55
  • 2
  • 10

2 Answers2

1

I'd reverse the logic: read the first word and check whether it starts with a quote, then dump the rest of the line:

std::string word;
while (std::cin >> word) {
    if (word[0] = '"')
        std::cout << "This is the first word: " << word.substr(1) << '\n';
    getline(cin, word); // read the rest of the line;
                        // extractor at top of loop will discard it
}
Pete Becker
  • 69,019
  • 6
  • 64
  • 147
0

You can use strings and you have to change your loop:

#include <iostream>
#include <fstream>
#include <limits>

using std::string;
using std::cout;

const auto ssmax = std::numeric_limits<std::streamsize>::max();

int main() {

    std::ifstream file{"input.txt"};    

    char ch;
    while ( file >> ch ) {
        // if a line start with a "
        if ( ch == '"') {
            string word;
            // read and output only the first word
            file >> word;
            cout << word << '\n';
        }
        // skip rest of the line
        file.ignore(ssmax,'\n');
    }

    return 0;
}

If the file named "input.txt" has this content:

Fruit name:
"Banana - yellow"
"Apple - red"
"Grape - purple"

The program outputs:

Banana
Apple
Grape
Bob__
  • 9,461
  • 3
  • 22
  • 31