Задачку предложил NaikoN. Суть задачи вот в чем: есть файл в котором записан некоторый текст на английском языке. Требуется вывести в алфавитном порядке все буквы которые встречаются в файле. Каждую букву выводить только один раз.
То есть, входными данными для программы может быть путь к файлу, конечно же можно прописать путь к файлу жестко, в коде, но это будет не красиво. Программа должна открывать файл в режиме чтения, и по порядку считывать каждый символ и сразу сравнивать, встречалась ли ранее такая буква, если — да, то не выводить текущую букву. Буквы, которые необходимо вывести на экран можно временно сохранять в строку.
Решение предоставил — NaikoN, вот его исходный код:
#include <iostream>
#include <vector>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
char buf[256];
cout<<"Enter file path: ";
cin>>buf;
ifstream in(buf);
if(!in)/// Если файл не найден
{
cout<<"file not found ";
return 0;
}
string str;
vector<char> vec_char, vec_final;
while(getline(in,str))///Пока есть строки в файле
{
for(unsigned int i=0;i<str.length();++i)
{
if(str[i]>='a'&&str[i]<='z'||str[i]>='A'&&str[i]<='Z')///если буква
{
///записывае в векторб но только маленькими буквами
vec_char.push_back(tolower(str[i]));
}
}
}
for(char j='a';j<='z';++j)///поиск букв в алфавитном порядке
{
for(int i=vec_char.size()-1;i>=0;--i)
{
if(vec_char[i]==(j))
{
vec_final.push_back(vec_char[i]);///если буква найденна
break;
}
}
}
for(auto &x:vec_final)cout<<x<<ends;///вывод на экран
return 0;
}
Содержимое файла: To be or not to be!!! Смотрим на результат работы программы:
Enter file path: file.txt benort
Комментарии
YourSpace_tym
// file_ltine.cpp : Defines the entry point for the console application. // created by YourSpace_tym #include "stdafx.h" #include "iostream" #include "fstream" #include "string" #include "cctype" #include "vector" using namespace std; bool is_leter_the_same(vector<char> p, int size, char symb){ for (int i = 0; i < size; i++) { if (symb == p[i]) return false; else if(i+1 == size) return true; } } int main() { string path; string alphabet = "abcdefghijklmnopqrstuvwxyz"; vector<char> letters_from_file; char k; int p = 0; cout << "Path to file : "; getline(cin, path); ifstream fin(path); while (!fin.eof() && fin.get(k)) { if (isalpha(k) && p == 0) { letters_from_file.insert(letters_from_file.end(), tolower(k)); } else if (isalpha(k) && is_leter_the_same(letters_from_file, letters_from_file.size(), k)) letters_from_file.insert(letters_from_file.end(), tolower(k)); if (letters_from_file.size() != 0) p = 1; } int m, n; for (int i = 0; i < letters_from_file.size(); i++){ for (int s = 0; s < letters_from_file.size(); s++) { for (int j = 0; j < alphabet.length(); j++) { if (letters_from_file[i] == alphabet[j]) m = j; if (letters_from_file[s] == alphabet[j]) n = j; } if (n > m) { int r = letters_from_file[i]; letters_from_file[i] = letters_from_file[s]; letters_from_file[s] = r; } } } for (int i = 0; i < letters_from_file.size(); i++) { cout << letters_from_file[i]; } cout << endl; return 0; }Shini_chi
#include <iostream> #include <fstream> #include <set> #include <iterator> #include <cctype> #include <Windows.h> using namespace std; int main () { SetConsoleCP (1251); SetConsoleOutputCP (1251); char name[20], str; set<char> character; cout << "Полное имя файла: "; cin >> name; ifstream fin(name); if (!fin.is_open()) cout << "Файл не может быть открыт!"; else while(!fin.eof()) { str = fin.get(); if (islower(str)) character.insert(str); } copy (character.begin(), character.end(), ostream_iterator<char>(cout, " ")); }vitaly prishepa
#include <bits/stdc++.h>
using namespace std;
int main()
{
setlocale(LC_ALL, «RUSSIAN»);
ifstream in;
ofstream out;
cout << «Введите имя файла: «;
char name[100];
cin >> name;
in.open(name);
out.open(«latin_out.txt»);
if (!in.is_open())
{
cerr << «Файл не может быть открыт! \n»;
out << «Файл не может быть открыт! \n»;
return 1;
}
int a[300]{};
string s;
while (in >> s)
{
for (int i = 0; i < s.size(); ++i)
a[s[i]]++;
}
for (int i = 0; i < 150; ++i)
if (a[i] && ((i >= ‘a’ && i <= ‘z’) || (i >= ‘A’ && i <= ‘Z’)))
cout << (char)i;
}
DenzelWashington
#include <iostream.h> #include <ctype.h> #include <fstream> using namespace std; main(){ int alpha[26] = {0}; char *path, ch; cout << "Enter Path: "; gets(path); ifstream input(path, ios::in); if(!input){ cerr <<"file could ot be opened!" << endl; exit(1);} while(input.get(ch)){ if(isalpha(ch)){ if(isupper(ch)){ alpha[ch - 65]++;} else alpha[toupper(ch) - 65]++;}} for(int i = 0; i <= 25; i++) if(alpha[i] != 0) cout << (char) (i + 65) << " "; return 0; }