powered by simpleCommunicator - 2.0.18     © 2024 Programmizd 02
Map
Форумы / C++ [игнор отключен] [закрыт для гостей] / Как исправить код?
3 сообщений из 3, страница 1 из 1
Как исправить код?
    #40113816
NN_41
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <algorithm>
using namespace std;
 
int main()
{
    setlocale(LC_ALL, "rus");
    int i = 0, n = 0, k = 0;
    bool flag = false;
    string s, word;
    int kvadrat = 1;
    do {
        cout << "Введите строку:";
        getline(cin, s);
        if (s.size() > 200)
            cout << "Строка слишком длинная, повторите ввод!" << endl;
    } while (s.size() > 200);
    while (s[i])
    {
        if (s[i] == ',')
            s[i] = ' ';
        i++;
    }
 
    stringstream s1(s);
    while (s1 >> word)
    {
        n++;
    }
 
    string* words = new string[n];
    stringstream s2(s);
    
    i = 0;
    
    while (s2 >> word)
    {
        if ((word[i] >= 0x30) && (word[i] <= 0x39)) {
            flag = true;
        }
        if (flag) {
            kvadrat *= atoi(word.c_str())* atoi(word.c_str());
            break;
        }
        if (word.size() == 4) {
            words[i] = word;
            i++;
            
        }
        
    }
   
    sort(words, words + i);
    for (int j = 0; j < n; j++)
        cout << words[j].c_str() << endl;
    cout << "Квадрат первого числа: " << kvadrat << endl;
    delete[] words;
    system("pause");
    return 0;
}


К примеру ввести: 12 adsd,aads ds
Должно вывести:
aads
adsd
Квадрат первого числа: 144
...
Рейтинг: 0 / 0
Как исправить код?
    #40114039
Пётр Седов
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
NN_41, это можно доработать напильником так:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

int main() {
  setlocale(LC_ALL, "rus");

  string text;
  int text_len;
  for (;;) {
    cout << "Введите строку:";
    getline(cin, text);
    text_len = text.length();
    if (text_len <= 200) {
      break;
    }
    cout << "Строка слишком длинная, повторите ввод!" << endl;
  }

  // заменяем запятые на пробелы
  for (int i = 0; i < text_len; i++) {
    if (text[i] == ',') {
      text[i] = ' ';
    }
  }

  // считаем количество слов, у которых длина = 4 элемента
  int words_count = 0;
  stringstream s1(text);
  string word;
  while (s1 >> word) {
    if (word.length() == 4) {
      words_count++;
    }
  }

  string* words = new string[words_count];
  int word_index = 0;
  bool has_number = false;
  int number;
  stringstream s2(text);
  while (s2 >> word) {
    int word_len = word.length();
    if (word_len == 4) {
      words[word_index] = word;
      word_index++;
    }

    if (!has_number) {
      bool all_elems_are_digits = true;
      for (int i = 0; i < word_len; i++) {
        char e = word[i];
        if (('0' <= e) && (e <= '9')) {
          // это цифра
        } else {
          all_elems_are_digits = false;
          break;
        }
      }
      if (all_elems_are_digits) {
        number = atoi(word.c_str());
        has_number = true;
      }
    }
  }

  sort(words, words + words_count);
  for (int i = 0; i < words_count; i++) {
    cout << words[i] << endl;
  }
  delete[] words;
  words = NULL;

  if (has_number) {
    cout << "Квадрат первого числа: " << number * number << endl;
  }

  system("pause");
  return 0;
}

Но 3 прохода по тексту -- это уж совсем неоптимально.
...
Рейтинг: 0 / 0
Как исправить код?
    #40114261
NN_41
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Пётр Седов, спасибо)
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / C++ [игнор отключен] [закрыт для гостей] / Как исправить код?
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали тему (1): Анонимы (1)
Читали форум (1): Анонимы (1)
Пользователи онлайн (9): Анонимы (6), Bing Bot 1 мин., Yandex Bot 1 мин., RePredeclared 8 мин.
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]