Организовать ввод строки, каждое слово в строке отделяется от других слов пробелами, их может быть неограниченное количество. Найти самое короткое слово в строке.
Для решения задачи прочитайте статью — Строки в С++. Определить символ пробела в строке можно с помощью функции isspace. Чтобы определить длину слова, воспользуйтесь функцией strlen. пример вывода программы:
Автор программы — Сергей Киях. Задача решена с использованием класса string, собственно поэтому кода получилось так мало.
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string s;
std::cout << "Enter string: ";
std::getline(std::cin, s);
std::stringstream ss(s);
std::string word(s);
while (ss >> s)
if (s.size() < word.size())
word = s;
std::cout << "Res: " << word << std::endl;
return 0;
}
Результат работы программы, показан ниже:
CppStudio.com
Enter string: Прокладывай себе дорогу силой. Res: себе
Комментарии
RodjeR
#include <iostream> #include <algorithm> #include <vector> #include <iterator> using namespace std; int main() { cout << "Input text = "; vector<string> vec_str (istream_iterator<string>(cin), {}); int count_alpha = 0; vector<int> long_word; int i, j; for (i = 0; i < vec_str.size(); ++i) { count_alpha = 0; for (j = 0; j < vec_str[i].length(); ++j) { count_alpha++; } long_word.push_back(count_alpha); } cout << "Most short word = " << vec_str[distance(long_word.begin(), find(long_word.begin(),long_word.end(), *min_element(long_word.begin(),long_word.end())))]; return 0; }YourSpace_tym
// smallest word.cpp : Defines the entry point for the console application. // created by YourSpace_tym #include "stdafx.h" #include "iostream" #include "string" #include "cctype" using namespace std; int main() { string line; cout << "string : "; getline(cin, line); int count_of_symbols = 0; int min = line.length(); int r = 0, s = 0; for (int i = 0; i < line.length(); i++) { if (isalpha(line[i])) count_of_symbols++; if ((isspace(line[i]) || (ispunct(line[i])) || (isalpha(line[i]) && i + 1 == line.length())) && (count_of_symbols < min && count_of_symbols != 0)) { min = count_of_symbols; if (i + 1 == line.length() && isalpha(line[i])) { s = i; r = s - count_of_symbols; } else { s = i - 1; r = s - count_of_symbols+1; } } if (isspace(line[i])) count_of_symbols = 0; } cout << "Min : "; for (int i = r; i <= s; i++) cout << line[i]; cout << endl; return 0; }