Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.68/19: Рейтинг темы: голосов - 19, средняя оценка - 4.68
0 / 0 / 0
Регистрация: 24.11.2014
Сообщений: 9
1

Как прочитать строку с клавиатуры с пробелами

07.05.2015, 23:50. Показов 3722. Ответов 16
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
как сделать так чтобы программа считывала с клавиатуры строку с пробелами в переменную name?

C++
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
 
using namespace std;
 
class automobile
{
public:
    char name;
    string tt, ft;
    int g, hp, fc, n, t;
    long p, p1;
    virtual void display(void){}
    virtual double price(void){ return p; }
    virtual double tax(void){ return t; }
};
 
class car :public automobile
{
public:
    car()
    {
        cout << "\t\tCar constrictor\nEnter the car name: ";
        cin >> name;
        cout << "\nEnter graduation year: ";
        cin >> g;
        cout << "\nEnter price of the car (RUB): ";
        cin >> p1;
        cout << "\nEnter transmission type (manual/automatic): ";
        cin >> tt;
        cout << "\nEnter engine power (hp): ";
        cin >> hp;
        cout << "\nEnter fuel type (gasoline/diesel): ";
        cin >> ft;
        cout << "\nEnter fuel consumption (l/100km): ";
        cin >> fc;
        cout << "\nEnter number of cars of this model: ";
        cin >> n;       
    }
    double price(void)
    {
        p = n * p1;
        return p;
    }
    double tax(void)
    {
        if (hp <= 150) 
        {
            t = hp * 0;
        }
        if (hp > 150 && hp <= 200) 
        {
            t = hp * 5;
        }
        if (hp > 200 && hp <= 250) 
        {
            t = hp * 7;
        }
        if (hp > 250) 
        {
            t = hp * 15;
        }
        return t;
    }
    void display(void)
    {
        cout << "\n\t\tCAR\n";
        cout << "Name: " << name << endl;
        cout << "Graduation year: " << g << endl;
        cout << "Price of the car: " << p1 << " RUB" << endl;
        cout << "Transmission type: " << tt << endl;
        cout << "Engine power: " << hp << " hp" << endl;
        cout << "Fuel type: " << ft << endl;
        cout << "Fuel consumption: " << fc << " l / 100km" << endl;
        cout << "Number of cars of this model: " << n << endl;
        cout << "The price of all vehicles: " << p << " RUB" << endl;
        cout << "Tax for the year: " << t << " RUB" << "\n\n" << endl;
    }
};
 
class bus :public automobile
{
public:
    bus()
    {
        cout << "\t\tBus constrictor\nEnter the bus name: ";
        cin >> name;
        cout << "\nEnter graduation year: ";
        cin >> g;
        cout << "\nEnter price of the bus (RUB): ";
        cin >> p1;
        cout << "\nEnter transmission type (manual/automatic): ";
        cin >> tt;
        cout << "\nEnter engine power (hp): ";
        cin >> hp;
        cout << "\nEnter fuel type (gasoline/diesel): ";
        cin >> ft;
        cout << "\nEnter fuel consumption (l/100km): ";
        cin >> fc;
        cout << "\nEnter number of buses of this model: ";
        cin >> n;
    }
    double price(void)
    {
        p = n * p1;
        return p;
    }
    double tax(void)
    {
        if (hp < 200)
        {
            t = hp * 5;
        }
 
        if (hp > 200)
        {
            t = hp * 10;
        }
        return t;
    }
    void display(void)
    {
        cout << "\n\t\tBUS\n";
        cout << "Name: " << name << endl;
        cout << "Graduation year: " << g << endl;
        cout << "Price of the bus: " << p1 << " RUB" << endl;
        cout << "Transmission type: " << tt << endl;
        cout << "Engine power: " << hp << " hp" << endl;
        cout << "Fuel type: " << ft << endl;
        cout << "Fuel consumption: " << fc << " l / 100km" << endl;
        cout << "Number of buses of this model: " << n << endl;
        cout << "The price of all vehicles: " << p << " RUB" << endl;
        cout << "Tax for the year: " << t << " RUB" << "\n\n" << endl;
    }
};
 
class minibus :public automobile
{
public:
    minibus()
    {
        cout << "\t\tMinibus constrictor\nEnter the minibus name: ";
        cin >> name;
        cout << "\nEnter graduation year: ";
        cin >> g;
        cout << "\nEnter price of the minibus (RUB): ";
        cin >> p1;
        cout << "\nEnter transmission type (manual/automatic): ";
        cin >> tt;
        cout << "\nEnter engine power (hp): ";
        cin >> hp;
        cout << "\nEnter fuel type (gasoline/diesel): ";
        cin >> ft;
        cout << "\nEnter fuel consumption (l/100km): ";
        cin >> fc;
        cout << "\nEnter number of minibuses of this model: ";
        cin >> n;
    }
    double price(void)
    {
        p = n * p1;
        return p;
    }
    double tax(void)
    {
        if (hp <= 150)
        {
            t = hp * 0;
        }
        if (hp > 150 && hp <= 200)
        {
            t = hp * 5;
        }
        if (hp > 200 && hp <= 250)
        {
            t = hp * 7;
        }
        if (hp > 250)
        {
            t = hp * 15;
        }
        return t;
    }
    void display(void)
    {
        cout << "\n\t\tMINIBUS\n";
        cout << "Name: " << name << endl;
        cout << "Graduation year: " << g << endl;
        cout << "Price of the minibus: " << p1 << " RUB" << endl;
        cout << "Transmission type: " << tt << endl;
        cout << "Engine power: " << hp << " hp" << endl;
        cout << "Fuel type: " << ft << endl;
        cout << "Fuel consumption: " << fc << " l / 100km" << endl;
        cout << "Number of minibuses of this model: " << n << endl;
        cout << "The price of all vehicles: " << p << " RUB" << endl;
        cout << "Tax for the year: " << t << " RUB" << "\n\n" << endl;
    }
};
 
int _tmain(int argc, _TCHAR* argv[])
{   
    string border = { "-------------------------------------------------------------------------------" };
    automobile* ca;
    automobile* bu;
    automobile* mi;
    char input;
 
    cout << "\t\tTypes of automobiles \n" << border << endl;
    while (1)
    {
        cout << "Enter 1 - for car\n " << "\nEnter 2 - for bus\n " << "\nEnter 3 - for minibus\n " << "\nEnter any key to exit\n " << endl;
        cin >> input;
 
        if (input == '1')
        {
            ca = new car();
            ca->price();
            ca->tax();
            ca->display();
        }
        else if (input == '2')
        {
            bu = new bus();
            bu->price();
            bu->tax();
            bu->display();
        }
        else if (input == '3')
        {
            mi = new minibus();
            mi->price();
            mi->tax();
            mi->display();
        }
        else
        {
            break;
            exit(0);
        }
    }
    system("pause");
    return 0;
 }
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
07.05.2015, 23:50
Ответы с готовыми решениями:

Как прочитать строку с пробелами из файла в одну переменную?
есть текстовый файл, в нем 3 строки как прочитать 1ую строку(она с пробелами) в 1ну переменную...

Прочитать строку с пробелами
#include &lt;iostream&gt; using namespace std; class cString { public: cString() { str ='\0';...

Считать с клавиатуры строку с пробелами
Помогите, пожалуйста, считать с клавиатуры строку с пробелами. Какой функцией пользоваться и как?...

Создать строку,ввод которой осуществляется с клавиатуры, состоящую из слов, разделенных пробелами
Создать строку,ввод которой осуществляется с клавиатуры, состоящую из слов, разделенных пробелами.

16
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
07.05.2015, 23:54 2
std::getline
0
Заблокирован
07.05.2015, 23:54 3
Цитата Сообщение от magnestic Посмотреть сообщение
C++
1
char name;
Это - место в памяти для одной буквы.
0
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
08.05.2015, 00:22 4
Правильно будет сказать символа.
0
0 / 0 / 0
Регистрация: 24.11.2014
Сообщений: 9
08.05.2015, 00:39  [ТС] 5
а где это можно реализовать? в main? если да, то каким образом? я уже натыкался и на getline, пробовал подключить conio.h и так сделать:
char name[500];
gets(name);
все равно ошибки выдает, короче окончательно запутался
0
Заблокирован
08.05.2015, 00:54 6
Сделайте
C++
1
string name;
А потом - рецепт из поста №2
0
0 / 0 / 0
Регистрация: 24.11.2014
Сообщений: 9
08.05.2015, 01:38  [ТС] 7
ругается
Миниатюры
Как прочитать строку с клавиатуры с пробелами  
0
Заблокирован
08.05.2015, 02:19 8
Цитата Сообщение от magnestic Посмотреть сообщение
ругается
Покажите код после изменений
0
0 / 0 / 0
Регистрация: 24.11.2014
Сообщений: 9
08.05.2015, 10:23  [ТС] 9
Изменил название переменной name на b. Сделал таким образом:
C++
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
 
using namespace std;
 
class automobile
{
public:
    string b, m, tt, ft;
    int g, hp, n, t;
    double fc;
    long p, p1;
    virtual void display(void){}
    virtual double price(void){ return p; }
    virtual double tax(void){ return t; }
};
 
class car :public automobile
{
public:
    car()
    {
        cout << "\t\tCar constrictor\nEnter the car brand: ";
        cin >> b;
        cout << "\nEnter the car model: ";
        cin >> m;
        cout << "\nEnter graduation year: ";
        cin >> g;
        cout << "\nEnter price of the car (RUB): ";
        cin >> p1;
        cout << "\nEnter transmission type (manual/automatic): ";
        cin >> tt;
        cout << "\nEnter engine power (hp): ";
        cin >> hp;
        cout << "\nEnter fuel type (gasoline/diesel): ";
        cin >> ft;
        cout << "\nEnter number of cars of this model: ";
        cin >> n;
        cout << "\nEnter fuel consumption (l/100km): ";
        cin >> fc;
    }
    double price(void)
    {
        p = n * p1;
        return p;
    }
    double tax(void)
    {
        if (hp <= 100) 
        {
            t = hp * 12;
        }
        if (hp > 100 && hp <= 125) 
        {
            t = hp * 25;
        }
        if (hp > 125 && hp <= 150) 
        {
            t = hp * 35;
        }
        if (hp > 150 && hp <= 175)
        {
            t = hp * 45;
        }
        if (hp > 175 && hp <= 200)
        {
            t = hp * 50;
        }
        if (hp > 200 && hp <= 225)
        {
            t = hp * 65;
        }
        if (hp > 225 && hp <= 250)
        {
            t = hp * 75;
        }
        if (hp > 250) 
        {
            t = hp * 150;
        }
        return t;
    }
    void display(void)
    {
        cout << "\n\t\tCAR\n";
        cout << "Brand: " << b << endl;
        cout << "Model: " << m << endl;
        cout << "Graduation year: " << g << endl;
        cout << "Price of the car: " << p1 << " RUB" << endl;
        cout << "Transmission type: " << tt << endl;
        cout << "Engine power: " << hp << " hp" << endl;
        cout << "Fuel type: " << ft << endl;
        cout << "Fuel consumption: " << fc << " l / 100km" << endl;
        cout << "Number of cars of this model: " << n << endl;
        cout << "The price of all vehicles: " << p << " RUB" << endl;
        cout << "Tax for the year: " << t << " RUB" << "\n\n" << endl;
    }
};
 
class bus :public automobile
{
public:
    bus()
    {
        cout << "\t\tBus constrictor\nEnter the bus brand: ";
        cin >> b;
        cout << "\nEnter the bus model: ";
        cin >> m;
        cout << "\nEnter graduation year: ";
        cin >> g;
        cout << "\nEnter price of the bus (RUB): ";
        cin >> p1;
        cout << "\nEnter transmission type (manual/automatic): ";
        cin >> tt;
        cout << "\nEnter engine power (hp): ";
        cin >> hp;
        cout << "\nEnter fuel type (gasoline/diesel): ";
        cin >> ft;
        cout << "\nEnter number of buses of this model: ";
        cin >> n;
        cout << "\nEnter fuel consumption (l/100km): ";
        cin >> fc;
    }
    double price(void)
    {
        p = n * p1;
        return p;
    }
    double tax(void)
    {
        if (hp <= 100)
        {
            t = hp * 15;
        }
        if (hp > 100 && hp <= 200)
        {
            t = hp * 26;
        }
 
        if (hp > 200)
        {
            t = hp * 55;
        }
        return t;
    }
    void display(void)
    {
        cout << "\n\t\tBUS\n";
        cout << "Brand: " << b << endl;
        cout << "Model: " << m << endl;
        cout << "Graduation year: " << g << endl;
        cout << "Price of the bus: " << p1 << " RUB" << endl;
        cout << "Transmission type: " << tt << endl;
        cout << "Engine power: " << hp << " hp" << endl;
        cout << "Fuel type: " << ft << endl;
        cout << "Fuel consumption: " << fc << " l / 100km" << endl;
        cout << "Number of buses of this model: " << n << endl;
        cout << "The price of all vehicles: " << p << " RUB" << endl;
        cout << "Tax for the year: " << t << " RUB" << "\n\n" << endl;
    }
};
 
class minibus :public automobile
{
public:
    minibus()
    {
        cout << "\t\tMinibus constrictor\nEnter the minibus brand: ";
        cin >> b;
        cout << "\nEnter the minibus model: ";
        cin >> m;
        cout << "\nEnter graduation year: ";
        cin >> g;
        cout << "\nEnter price of the minibus (RUB): ";
        cin >> p1;
        cout << "\nEnter transmission type (manual/automatic): ";
        cin >> tt;
        cout << "\nEnter engine power (hp): ";
        cin >> hp;
        cout << "\nEnter fuel type (gasoline/diesel): ";
        cin >> ft;
        cout << "\nEnter number of minibuses of this model: ";
        cin >> n;
        cout << "\nEnter fuel consumption (l/100km): ";
        cin >> fc;
    }
    double price(void)
    {
        p = n * p1;
        return p;
    }
    double tax(void)
    {
        if (hp <= 100)
        {
            t = hp * 12;
        }
        if (hp > 100 && hp <= 125)
        {
            t = hp * 25;
        }
        if (hp > 125 && hp <= 150)
        {
            t = hp * 35;
        }
        if (hp > 150 && hp <= 175)
        {
            t = hp * 45;
        }
        if (hp > 175 && hp <= 200)
        {
            t = hp * 50;
        }
        if (hp > 200 && hp <= 225)
        {
            t = hp * 65;
        }
        if (hp > 225 && hp <= 250)
        {
            t = hp * 75;
        }
        if (hp > 250)
        {
            t = hp * 150;
        }
        return t;
    }
    void display(void)
    {
        cout << "\n\t\tMINIBUS\n";
        cout << "Brand: " << b << endl;
        cout << "Model: " << m << endl;
        cout << "Graduation year: " << g << endl;
        cout << "Price of the minibus: " << p1 << " RUB" << endl;
        cout << "Transmission type: " << tt << endl;
        cout << "Engine power: " << hp << " hp" << endl;
        cout << "Fuel type: " << ft << endl;
        cout << "Fuel consumption: " << fc << " l / 100km" << endl;
        cout << "Number of minibuses of this model: " << n << endl;
        cout << "The price of all vehicles: " << p << " RUB" << endl;
        cout << "Tax for the year: " << t << " RUB" << "\n\n" << endl;
    }
};
 
int _tmain(int argc, _TCHAR* argv[])
{   
 
    string b, border = { "-------------------------------------------------------------------------------" };
    std::getline(std::cin, b);
    automobile* ca;
    automobile* bu;
    automobile* mi;
    char input;
 
    cout << "\t\t\tTypes of automobiles \n" << border << endl;
    while (1)
    {
        cout << "Enter 1 - for car\n " << "\nEnter 2 - for bus\n " << "\nEnter 3 - for minibus\n " << "\nEnter any key to exit\n " << endl;
        cin >> input;
 
        if (input == '1')
        {
            ca = new car();
            ca->price();
            ca->tax();
            ca->display();
        }
        else if (input == '2')
        {
            bu = new bus();
            bu->price();
            bu->tax();
            bu->display();
        }
        else if (input == '3')
        {
            mi = new minibus();
            mi->price();
            mi->tax();
            mi->display();
        }
        else
        {
            break;
            exit(0);
        }
    }
    system("pause");
    return 0;
 }
но появились следующие косяки - при компиляции чтобы появилось окно с выбором автомобиля нужно нажать какой-либо символ; ввожу к примеру nissan nissan, считывает, но в итоге он принимает значение после пробела за модель автомобиля, а модель не дает ввести.
Миниатюры
Как прочитать строку с клавиатуры с пробелами  
Изображения
 
0
7792 / 6559 / 2984
Регистрация: 14.04.2014
Сообщений: 28,669
08.05.2015, 10:51 10
Говорили же про getline(). Для операции >> пробел - разделитель как и конец строки.
0
0 / 0 / 0
Регистрация: 24.11.2014
Сообщений: 9
08.05.2015, 11:17  [ТС] 11
не совсем понимаю
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
08.05.2015, 11:27 12
Цитата Сообщение от magnestic Посмотреть сообщение
не совсем понимаю
оператор>> читает элементы по "словам", т.е. до первого пробельного разделителя (пробел, новая строка, табулятор и т.д.)
Чтобы прочитать строку (включая пробелы) в переменную std::string нужно использовать упомянутую ранее getline.
0
46 / 35 / 24
Регистрация: 16.03.2015
Сообщений: 179
08.05.2015, 11:29 13
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream.h>
 
void main(void)
{
  char *name;
  int buf_size = 100;
  int count = 0;          // Счетчик символов.
 
  name = new char[buf_size];
 
  // Обратите внимание, что выходной буфер очищается.
  cout << "\n Enter your name:" << endl;
  cin.getline(name, buf_size);
 
  count = cin.gcount();
  // GetLine() сохраняет новую строку, gcount() будет считать его как ввод.
  cout << "\nName character count: " << count - 1;
}
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
08.05.2015, 11:40 14
Цитата Сообщение от Shvonder Посмотреть сообщение
#include <iostream.h>
В современных компиляторах такого уже давно нет.
0
46 / 35 / 24
Регистрация: 16.03.2015
Сообщений: 179
08.05.2015, 11:48 15
Цитата Сообщение от Tulosba Посмотреть сообщение
В современных компиляторах такого уже давно нет.
Да. Не заметил. Изменить на "#include <iostream>"
Кликните здесь для просмотра всего текста
Как прочитать строку с клавиатуры с пробелами
0
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
08.05.2015, 16:40 16
Цитата Сообщение от Shvonder Посмотреть сообщение
Кликните здесь для просмотра всего текста
Закопать и больше не тревожить. Так писали лет 20 назад (до первого стандарта, который приняли ещё в 1998)

Добавлено через 1 минуту
Мда.. не знал что даже в офф. доке приводят код, где динамически выделенную память не освобождают.
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
08.05.2015, 17:39 17
Цитата Сообщение от MrGluck Посмотреть сообщение
даже в офф. доке приводят код, где динамически выделенную память не освобождают
Так это ж демка. Причем совершенно другой задачи (не работа с памятью). К тому же: "само освободится при выходе" А вообще, можно было бы и массив на стеке сделать, конечно. Соточка байт уж при любых раскладах влезет.
P.S. меня ещё void main() смутил. Раньше только у MS такое встречал, а тут на те ... былдер.
Не знаю, поддерживают ли они до сих пор такую сигнатуру (как MS) или нет.
0
08.05.2015, 17:39
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
08.05.2015, 17:39
Помогаю со студенческими работами здесь

Ввести с клавиатуры строку символов, состоящую из слов, разделенных пробелами, и записать ее в файл
Ввести с клавиатуры строку символов, состоящую из слов, разделенных пробелами, и записать ее в...

Прочитать строку с клавиатуры (признак окончания строки – нажатие Enter)
Прочитать строку с клавиатуры (признак окончания строки – нажатие Enter) и добавить его в другой,...

C клавиатуры вводят строку, в которой есть числа, роздалены 1 или несколькю пробелами. Вывести на екран найбольшее
Я токо С++ начал учить а уже дали проект, очень нужно прошу помоч, знаю задача не сложна, помогите...

Ввести с клавиатуры строку, состоящую из целых чисел, разделенных пробелами. Найти минимальное число и вывести на экран
Я вроде чё-то понял, но вроде и нет :D. Можете подсказать, где и что не так? А то не понимаю, что...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
17
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru