Другие языки программирования и технологии

Как посчитать пробелы в тексте С++? Ток не 1 строку а пробелы)

Роман *
Роман *
233
#include <iostream>
#include <vector>
#include <fstream>
#include <map>
#include <string>
using namespace std;
class Counter {
public:
Counter() = delete;
explicit Counter(const char* cstr) {
parse(string(cstr));
}
explicit Counter(const string& str) {
parse(str);
}
explicit Counter(const vector<string>& strs) {
for (const auto &str : strs) parse(str);
}
explicit Counter(ifstream& file) {
if (file.is_open() && !file.bad()) {
string str;
while (getline(file, str)) parse(str);
}
}
bool contains(const char sign)const {
return box_.count(sign) > 0;
}
size_t count_if(const char sign) {
if (contains(sign)) return box_.find(sign)->second;
return 0u;
}
private:
map<char, size_t> box_;
void parse(const string& str) {
for (const auto sign : str) ++box_[sign];
}
};
int main() {
const auto space = ' ';

char a[] = "111 222 333 444 555 666 777";
Counter oa(a);
cout << R"(spaces in the const char* 'a': )" << oa.count_if(space);
cout.put('\n');

const string b = "11 22 33 44 55";
Counter ob(b);
cout << R"(spaces in the string 'b': )" << ob.count_if(space);
cout.put('\n');

const vector<string> с{ a, b };
Counter oc(с);
cout << R"(spaces in the vector<string> 'c': )" << oc.count_if(space);
cout.put('\n');

ifstream d("text.txt");
if (d.is_open()) {
Counter od(d);
cout << R"(spaces in the file 'd': )" << od.count_if(space);
cout.put('\n');
d.close();
} else {
cout << R"(file 'text.txt' not found\n)";
}
system("pause");
}
ИМ
Игорь Мясниченко
97 922
Лучший ответ
#include <iostream>
using namespace std;
int main() {
 setlocale(LC_ALL, "Russian");
 char s[256];
 cin.getline(s, 256);
 int count = 0;
 for (int i = 0; s[i]; count += s[i] == ' ', ++i);
 cout << count << endl;
 cin.get();
 return 0;
}
читать файл посимвольно, если символ==' ', то увеличить счетчик, если конец файла - выдать результат.
if(str[i] == ' ') spaceCount++;
С*
Сер ***
69 623
#include < iostream >
#include < string >

using namespace std;

void main()
{
setlocale(LC_ALL, "rus");
cout << "Введите строку ";
string s;
getline(cin, s);
unsigned sum = 0;
for (char c : s)
{
if (c == ' ')
++sum;
}
cout << "В строке " << sum << " пробелов";
cin.get(); cin.get();
}
Александр Горелов Если читать из файла:
Запуск только через *.exe, иначе не видит файла для считывания.
#include < iostream >
#include < fstream >
#include < string >

using namespace std;

void main()
{
setlocale(LC_ALL, "rus");
string s;
ifstream fin("5.txt"); // (ВВЕЛИ НЕ КОРРЕКТНОЕ ИМЯ ФАЙЛА)
while (fin)
{
string t;
getline(fin, t);
s += t;
}
fin.close();

unsigned sum = 0;
for (char c : s)
{
if (c == ' ')
++sum;
}
cout << "В строке " << sum << " пробелов";
cin.get(); cin.get();
}

Похожие вопросы