помогите решить задачу
Дан файл, содержащий произвольный текст, разбитый на строки. Подсчитать сколько строк начинается с буквы, введенной пользователем.
|
Примерно так
Код:
#include <stdio.h>
void main()
{
unsigned char c; // введенный символ
char buf[1024]; // буфер для строки
int count=0; // подсчет количества строк начинающейся с введенного символа
scanf("%c", &c); // ввод символа
FILE* f = fopen("st1.txt", "r"); // открытие файла
while(!feof(f)) // пока не достигнут конец файла
{
fscanf(f, "%s", &buf); // считать строку
printf("%s\n", buf); // вывести строку
if (buf[0] == c) // совпадает ли начало строки и введенный символ
{
printf("equal\n");
count++;
}
}
fclose(f);
}
|
Код:
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
int main()
{
std::ifstream ifs("file.txt");
assert(ifs);
std::string str{std::istreambuf_iterator<char>(ifs), {}};
std::vector<std::string> lines;
boost::split(lines, str, boost::is_any_of("\n\r"), boost::token_compress_on);
for (auto &s : lines) std::cout << s << "\n";
std::cout << "\n\nEnter letter: ->";
char ch;
std::cin >> ch;
std::cout << "Count of lines beginning on " << ch << ": "
<< std::count_if(lines.begin(), lines.end(), [=](std::string &s){return ch == s.front();})
<< "\n";
std::cout << "Done.\n";
}
|
Время: 21:33.
© OSzone.net 2001-