Как выделить первое слово из символьного массива?

Имеется текстовый файл in.txt. Требуется вывести на экран строки файла, начинающиеся с заданного слова. Слово задается вводом с клавиатуры. Считываю файл построчно в цикле, не могу сообразить как из buff вытащить первое слово, чтобы сравнить с введенным.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    char word[20];
    cin.getline(word, 20);
    ofstream fout;
    fout.open("in.txt");
    fout << "Today it's raining. " << endl;
    fout << "Yesterday it was raining. "<< endl;
    fout << "Today it's cold. "<< endl;
    fout << "Tomorrow will be no rain Today. "<< endl;
    fout << "Today it's windy. "<< endl;
    fout << "Today it's sunny. "<< endl;
    FILE * ptrFile = fopen("in.txt", "rb");
    char buff[50];
    ifstream fin;
    fin.open("in.txt");
    while(!feof(ptrFile)){
    fin.getline(buff, 50);
    if()// условие вывода строки
    cout << buff;

    }
    return 0;
}


Ответы (1 шт):

Автор решения: Maggot

Для этого есть starts_with (с++20 я думаю в 2021 году у вас современный компилятор)

Я бы предложил сделать так:

  1. чиатем файл по строчно через std::getline
  2. првоеряем через starts_with что строка начинается с паттерна

Вот пример кода

#include <string>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <cassert>
 
int main() {
  std::string pattern{"Hello"};
  std::filesystem::path pth{std::filesystem::current_path() / "data"};
  std::ifstream ifs{pth, std::ios::in };
  assert(ifs.is_open() && "Error open file");

  for (std::string l; std::getline(ifs, l); ) {
    if (l.starts_with(pattern)) {
      std::cout << "Match! " << l << std::endl;
    }
  }

  return 0;
}
→ Ссылка