Войти

Показать полную графическую версию : помогите решить задачу


qweunhiu
31-05-2015, 23:25
Дан файл, содержащий произвольный текст, разбитый на строки. Подсчитать сколько строк начинается с буквы, введенной пользователем.

mrcnn
02-06-2015, 11:24
Примерно так
#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);

}

Yuron_477
25-06-2015, 15:56
#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";
}




© OSzone.net 2001-2012