简体   繁体   中英

C++ - if-statement only works for one iteration of while loop

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!

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM