Ошибка идентификатор getline не определен

I have problem with getline().

I tried many examples and read other solutions, but that didn’t solve my problem. I still have information 'getline: identifier not found'.

I included
<stdio.h> <tchar.h> <iostream> <conio.h> <stdlib.h> <fstream> and still nothing.

#include "stdafx.h"

using namespace std;

int main(int argc, _TCHAR* argv[])
{
    string line;
    getline(cin, line);
    cout << "You entered: " << line << endl;
}

What do I need to do now?

I use Windows 7 64 bit and Visual Studio 2013.

I have problem with getline().

I tried many examples and read other solutions, but that didn’t solve my problem. I still have information 'getline: identifier not found'.

I included
<stdio.h> <tchar.h> <iostream> <conio.h> <stdlib.h> <fstream> and still nothing.

#include "stdafx.h"

using namespace std;

int main(int argc, _TCHAR* argv[])
{
    string line;
    getline(cin, line);
    cout << "You entered: " << line << endl;
}

What do I need to do now?

I use Windows 7 64 bit and Visual Studio 2013.

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Ask Question

Asked
7 years, 10 months ago

Modified
7 years, 10 months ago

Viewed
154 times

-5

Error:identifier «getline» is undefined. What am I overlooking?

#include "stdafx.h"
#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
string str;
getline(cin, str);
getch();
return 0;
}

  • c++

Improve this question

asked Aug 9, 2015 at 22:08

Luke Weaver's user avatar

Luke WeaverLuke Weaver

432 silver badges6 bronze badges

1

  • 3

    Include the right header file. See en.cppreference.com/w/cpp/string/basic_string/getline

    – juanchopanza

    Aug 9, 2015 at 22:09

Add a comment
 | 

1 Answer

Sorted by:

Reset to default

1

You need to add

#include <string>

to be able to use std::string and std::getline(). Without that even the line

string str;

will most likely produce a compiler error.

Improve this answer

answered Aug 9, 2015 at 22:14

R Sahu's user avatar

R SahuR Sahu

204k14 gold badges153 silver badges269 bronze badges

2

  • alright that works but I also had to change getch() to _getch

    – Luke Weaver

    Aug 9, 2015 at 22:24

  • @LukeWeaver, getch() is a non-standard function. I don’t use it at all and can’t comment on it. I am glad you figured out what works.

    – R Sahu

    Aug 9, 2015 at 22:31

Add a comment
 | 

Your Answer

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you’re looking for? Browse other questions tagged

  • c++

or ask your own question.

  • The Overflow Blog
  • Part man. Part machine. All farmer. 

  • Throwing away the script on testing (Ep. 583)

  • Featured on Meta
  • Statement from SO: June 5, 2023 Moderator Action

  • Starting the Prompt Design Site: A New Home in our Stack Exchange Neighborhood

  • Does the policy change for AI-generated content affect users who (want to)…

  • Temporary policy: Generative AI (e.g., ChatGPT) is banned

Related

0

What am I missing? GetLine function (C++)

0

problem with getline() function

0

c++ getline() function

1

getline function not working

1

Using the getline()

1

getline() function in C++ does not work

1

How can I get the getline operator to work?

0

Having an issue using the getline function

0

C++ getline() function not working as intended

2

Problems using getline

Hot Network Questions

  • Asylee Green Card holder plans to visit Canada

  • How to understand 之所以

  • What do you use Luxury gemstones for?

  • PI is asking me to do administrative work like submitting reports for grants

  • Italic text is smaller than regular text when using clearpage and the scrlayer-scrpage package

  • Why is loud music much louder after pausing and resuming it?

  • What government policies has Russia implemented to revive its domestic industries, after economic sanctions were imposed on them?

  • What is a tight narrow space between things that are in tight contact with each other called in everyday English?

  • Is ammunition a consumable magic item?

  • What telescope is Polish astronomer Kazimierz Kordylewski holding in this April 1964 photo at the Jagiellonian University Observatory in Krakow?

  • What does a set of pencils contain when we know that pencils are not physically present in the set?

  • while loop countdown with sleep doesnt work?

  • Can omnipotent beings exist?

  • How dangerous is tossing equipment off the ISS?

  • Is my employer allowed to make me work without pay?

  • How does «thou» equal «oneg»?

  • When designing antennas which speed of light should be used?

  • Compare new txt file with old txt file and remove all data that matches

  • Seeking Notable Responses to «Why the Trans Inclusion Problem cannot be Solved» by Tomas Bogardus

  • Has anyone tried to make 3-D chess in real life?

  • What parts of a spaceship would still work 100 million years later?

  • What characterizes a future-proof ebike drive system?

  • Can you cast Prismatic Sphere when you are adjacent to a wall?

  • Do more legislative seats make Gerrymandering harder?

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

richlime

0 / 0 / 0

Регистрация: 05.12.2018

Сообщений: 16

1

02.12.2019, 19:00. Показов 19930. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

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
#include <string.h>
#include <windows.h>
#include <conio.h>
#include <iostream>
#include <iomanip>
 
using namespace std;
 
class wow
{
    struct time
    {
        int day, mnt, year;
        string name;
        time* next;
    } *beg, * end;
public:
    wow() { beg = end = 0; };               // конструктор
    wow(const wow&);                // конструктор копирования
    ~wow();
    void addel();
    void show();
    void search();
    void delel();
};
 
wow::wow(const wow& temp) //конструктор копирования
{
    beg = new time;
    end = new time;
    if (!temp.beg) beg = end = 0;
    else
        if (!temp.beg->next)
        {
            beg->day = temp.beg->day;
            beg->mnt = temp.beg->mnt;
            beg->name = temp.beg->name;
            beg->year = temp.beg->year;
            beg->next = new time;
            beg->next = 0;
            end = beg;
        }
        else
        {
            beg->day = temp.beg->day;
            beg->mnt = temp.beg->mnt;
            beg->name = temp.beg->name;
            beg->year = temp.beg->year;
            time* tp = beg;
            time* tmp = temp.beg;
            tmp = tmp->next;
            while (tmp->next)
            {
                beg->next = new time;
                beg = beg->next;
                beg->day = tmp->day;
                beg->mnt = tmp->mnt;
                beg->name = tmp->name;
                beg->year = tmp->year;
                tmp = tmp->next;
 
            };
            beg->next = new time;
            beg = beg->next;
            beg->day = tmp->day;
            beg->mnt = tmp->mnt;
            beg->name = tmp->name;
            beg->year = tmp->year;
            beg->next = new time;
            beg->next = 0;
            end = beg;
            beg = tp;
        }
}
 
 
void wow::addel()       //добавление элемента
{
    system("cls");
    time* elem = new time;
    cin.clear(); cin.ignore(100, 'n');
    cout << " Введите название события: ";
    getline(cin, elem->name);
    cout << " Введите день, месяц и год: ";
    cin >> elem->day >> elem->mnt >> elem->year;
    if (beg == 0)
    {
        beg = new time;
        beg->day = elem->day;
        beg->mnt = elem->mnt;
        beg->year = elem->year;
        beg->name = elem->name;
        beg->next = 0;
        end = new time;
        end = beg;
 
    }
    else
    {
        end->next = new time;
        end = end->next;
        end->day = elem->day;
        end->mnt = elem->mnt;
        end->year = elem->year;
        end->name = elem->name;
        end->next = 0;
    }
}
 
void wow::delel()       //удаление элемента из очереди
{
    system("cls");
    if (!beg)
    {
        cout << " Очередь пуста. Что вы тут забыли? Нажмите что-нибудь...";
        cin.get();
    }
    else
        if (!beg->next)
        {
            cout << " Единственная запись удалена. Возрадуйтесь.";
            delete beg;
            delete end;
            cin.get();
        }
        else
        {
            cout << " Первая запись удалена. Воздрадуйтесь.";
            time* temp = beg;
            beg = beg->next;
            delete temp;
            cin.get();
        }
 
}
 
void wow::search()      //поиск элемента по дате
{
    system("cls");
    if (!beg)
    {
        cout << " Очередь пуста. Что вы тут забыли? Нажмите что-нибудь...";
        cin.get();
    }
    else
    {
        time* temp = beg;
        int year, month, day, fl = 0;
        cout << " Введите искомую дату через пробел" << endl;
        cin >> day >> month >> year;
        while (temp->next)
        {
            if ((temp->day == day) && (temp->mnt == month) && (temp->year == year))
            {
                cout << " Событие найдено! Это: " << temp->name << endl << " Нажмите что-то..." << endl;
                cin.get();
                fl = 1;
                break;
            }
            temp = temp->next;
        }
        delete temp;
        if (!fl) { cout << " Событие не найдено. Нажмите что-то" << endl; cin.get(); }
    }
}
 
 
void wow::show()    // вывод таблицы
{
    if (!beg) { cout << " Список пуст." << endl; }
    else
    {
        cout << "------------------------------------------------------------------------" << endl;
        cout << "|                 Название события                 | День | Месяц | Год |" << endl;
        time* temp = beg;
        while (temp)
        {
            cout << "|" << setw(50) << temp->name << "|" << setw(6) << temp->day << "|" << setw(7) << temp->mnt << "|" << setw(5) << temp->year << "|" << endl;
            temp = temp->next;
            if (!temp) break;
        }
        cout << "-------------------------------------------------------------------------" << endl;
    }
}
 
wow::~wow()
{
    time* temp = beg;
    if (beg) {
        while (beg->next) { beg = beg->next; delete temp; temp = beg; }
        delete end;
    }
}
wow perk;
void workingcopy(const wow)
{
    system("cls");
    wow perk3(perk);
    perk3.show();
    cin.get();
    cin.get();
}
 
 
 
int main()
{
    wow perk;
    wow perk2(perk);
    while (1)
    {
 
        system("cls");
        cout << " 1 - Добавление элемента в певую очередь" << endl;
        cout << " 2 - Добавление элемента во вторую очередь" << endl;
        cout << " 3 - Просмотр очереди" << endl;
        cout << " 4 - Поиск в первой очереди по дате" << endl;
        cout << " 5 - Поиск во второй очереди по дате" << endl;
        cout << " 6 - Удаление элемента из первой очереди" << endl;
        cout << " 7 - Удаление элемента из первой очереди" << endl;
        cout << " 8 - Демонстрация работы конструктора копирования" << endl;
        cout << " 9 - Выход" << endl;
        cout << " Ваш выбор: ";
        char i = cin.get();
        switch (i) {
        case '1': perk.addel(); break;
        case '2': perk2.addel(); break;
        case '3': {system("cls"); cout << " n Первая очередь:" << endl; perk.show();  cout << " Вторая очередь:" << endl; perk2.show();  cout << " Нажмите что-нибудь..." << endl; cin.get(); cin.get();break;}
        case '4': perk.search(); break;
        case '5': perk2.search(); break;
        case '6': perk.delel(); break;
        case '7': perk2.delel(); break;
        case '8': workingcopy(perk); break;
        case '9': return 0; break;
        }
    }
}

Подскажите, пожалуйста, выдает ошибку «E0020 идентификатор «getline» не определен» и «C3861 getline: идентификатор не найден». Что исправить надо? Строчка 83



0



Kislorod1234

0 / 0 / 0

Регистрация: 15.05.2016

Сообщений: 12

1

02.02.2017, 19:04. Показов 14916. Ответов 4

Метки нет (Все метки)


Ругается на getline , пишет идентификатор не найден

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
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <clocale>
 
int main()
{
    setlocale(LC_ALL, "rus");
    string  str1, str2, str;
    string  f_name1, f_name2;
    cout << "VV. name file 1 n" << endl;
    getline (cin, f_name1);
    cout << "VV. name file 2 n" << endl;;
    getline (cin, f_name2);
    ifstream f;
    f.open (f_name1, ios_base::in);
    ifstream g;
    g.open(f_name2, ios_base::in);
    int j = 0;
    while (!f.eof())
    {
        getline(f, str1, '');
        getline(g, str2, '');
        if (!Comp(str1, str2)) j=Put(str, str2,j);
    }
    f.close();
    g.close();
    //запись в файл
    system("pause");
    return 0;
}

Подскажите в чем проблема

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

zss

Модератор

Эксперт С++

12627 / 10125 / 6097

Регистрация: 18.12.2011

Сообщений: 27,158

02.02.2017, 19:28

2

Лучший ответ Сообщение было отмечено Kislorod1234 как решение

Решение

Нету

C++
1
#include <string>

а cstring Не надо

Да, и зачем Вам локализация, если русский текст не используете

1

0 / 0 / 0

Регистрация: 15.05.2016

Сообщений: 12

03.02.2017, 08:35

 [ТС]

3

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

Добавлено через 31 минуту
Еще не могу понять почему ругается на cin.getline(f,str,»); , я хочу дописать строку str в конец файла f

0

Эксперт CЭксперт С++

5094 / 2279 / 332

Регистрация: 20.02.2013

Сообщений: 5,598

Записей в блоге: 19

03.02.2017, 09:19

4

 Комментарий модератора 
Kislorod1234, пожалуйста, прочитайте правила форума.
Особое внимание обратите на пункты 4.4 и 5.16.

.

0

Модератор

Эксперт С++

12627 / 10125 / 6097

Регистрация: 18.12.2011

Сообщений: 27,158

03.02.2017, 09:54

5

Цитата
Сообщение от Kislorod1234
Посмотреть сообщение

cin.getline(f,str,»);

std::getline и istream::getline — это разные функции.
Читайте синтаксис в справке.
Кстати, она вызывается клавишей F1 (текстовый курсор должен стоять на том, о чем хотите получить справку).

0

For your first error, I think that the problem is in this declaration:

 const float APRICE = 6.00,
       float CPRICE = 3.00;

In C++, to declare multiple constants in a line, you don’t repeat the name of the type. Instead, just write

 const float APRICE = 6.00,
             CPRICE = 3.00;

This should also fix your last error, which I believe is caused by the compiler getting confused that CPRICE is a constant because of the error in your declaration.

For the second error, to use getline, you need to

#include <string>

not just

#include <cstring>

Since the getline function is in <string> (the new C++ string header) and not <cstring> (the old-style C string header).

That said, I think you’ll still get errors from this, because movieName is declared as an int. Try defining it as a std::string instead. You might also want to declare your other variables as floats, since they’re storing real numbers. More generally, I would suggest defining your variables as you need them, rather than all up at the top.

Hope this helps!

For your first error, I think that the problem is in this declaration:

 const float APRICE = 6.00,
       float CPRICE = 3.00;

In C++, to declare multiple constants in a line, you don’t repeat the name of the type. Instead, just write

 const float APRICE = 6.00,
             CPRICE = 3.00;

This should also fix your last error, which I believe is caused by the compiler getting confused that CPRICE is a constant because of the error in your declaration.

For the second error, to use getline, you need to

#include <string>

not just

#include <cstring>

Since the getline function is in <string> (the new C++ string header) and not <cstring> (the old-style C string header).

That said, I think you’ll still get errors from this, because movieName is declared as an int. Try defining it as a std::string instead. You might also want to declare your other variables as floats, since they’re storing real numbers. More generally, I would suggest defining your variables as you need them, rather than all up at the top.

Hope this helps!

#include<iostream>   
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include<fstream>
#include<string>

using namespace std;

  int countLines( ifstream& in  )
    {
        int count = 0;
        char line[80];
        if ( in.good() )
        {
            //while ( !feof( in ) )
                while( getline( in,line ) ) count++;
            in.seekg(ios::beg);
        }
        return count;
    }

No matching function for call get line
What does it mean?
I have included all of the headers but why I still can not call get line?

asked Jul 16, 2013 at 6:58

Pramono Wang's user avatar

1

You need to use a std::string instead of a character array for calling string’s getline() function. Replace your char line[80] with a std::string line and it will work.

Check the documentation here http://www.cplusplus.com/reference/string/string/getline/

answered Jul 16, 2013 at 6:59

Salgar's user avatar

SalgarSalgar

7,5471 gold badge25 silver badges39 bronze badges

1

#include<iostream>   
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include<fstream>
#include<string>

using namespace std;

  int countLines( ifstream& in  )
    {
        int count = 0;
        char line[80];
        if ( in.good() )
        {
            //while ( !feof( in ) )
                while( getline( in,line ) ) count++;
            in.seekg(ios::beg);
        }
        return count;
    }

No matching function for call get line
What does it mean?
I have included all of the headers but why I still can not call get line?

asked Jul 16, 2013 at 6:58

Pramono Wang's user avatar

1

You need to use a std::string instead of a character array for calling string’s getline() function. Replace your char line[80] with a std::string line and it will work.

Check the documentation here http://www.cplusplus.com/reference/string/string/getline/

answered Jul 16, 2013 at 6:59

Salgar's user avatar

SalgarSalgar

7,5471 gold badge25 silver badges39 bronze badges

1

У меня проблема с getline(),
Я пробовал много примеров и читал другие решения, но это не решило мою проблему. У меня еще есть информация 'getline: identifier not found',
я включен
<stdio.h> <tchar.h> <iostream> <conio.h> <stdlib.h> <fstream> и до сих пор ничего.

#include "stdafx.h"
using namespace std;

int main(int argc, _TCHAR* argv[])

{

string line;
getline(cin, line);
cout << "You entered: " << line << endl;

}

Что мне нужно сделать сейчас? Я использую Win7 64bit, MSVS2013.

1

Решение

Привыкнуть просто чтение документации для языковых функций, которые вы используете.
Соотношение совершенно ясно, что std::getline может найти в string,

#include <string>

8

Другие решения

Это должно исправить это:

#include "stdafx.h"#include <iostream>
#include <string>

using namespace std;

int main(int argc, _TCHAR* argv[]){
string line;
getline(cin, line);
cout << "You entered: " << line << endl;
}

5

#include "stdafx.h"#include <iostream>
#include <string>
using namespace std;
int main(int argc, _TCHAR* argv[]){
string line;
/*To consume the whitespace or newline between the end of a token and the
beginning of the next line*/

// eat whitespace
getline(cin >> ws, line);
cout << "You entered: " << line << endl;
}

0

#include <string>

Кстати, в учебнике «Программирование С ++» Мурача ошибочно говорится, что getline () находится в заголовке iostream (стр. 71), что может привести к некоторой путанице.

0

Here’s the code:

#include "stdafx.h"
#include <iostream>

using namespace std;

int i, j, l, r1, r2, r3, n1, n2, n3, n4, rII, rIII;

string msg;

int rotor1[26] = { 4,10,12,5,11,6,3,16,21,25,13,19,14,22,24,7,23,20,18,15,0,8,1,17,2,9 };
int rotor2[26] = { 0,9,3,10,18,8,17,20,23,1,11,7,22,19,12,2,16,6,25,13,15,24,5,21,14,4 };
int rotor3[26] = { 1,3,5,7,9,11,2,15,17,19,23,21,25,13,24,4,8,22,6,0,10,12,20,18,16,14 };
int reflec[26] = { 24,17,20,7,16,18,11,3,15,23,13,6,14,10,12,8,4,1,5,25,2,22,21,9,0,19 };
char base[26] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
void RotorInput() {
	cout << "Input initial positions (0 to 25):n";
	cout << "First rotor: ";
	cin >> r1;
	cout << "Second rotor: ";
	cin >> r2;
	cout << "Third rotor: ";
	cin >> r3;
}
void RotorInitialization() {
	rotate(rotor1, rotor1 + r1, rotor1 + 26);
	rotate(rotor2, rotor2 + r2, rotor2 + 26);
	rotate(rotor2, rotor2 + r2, rotor2 + 26);
}
void MessageInput() {
	cout << "Input your message/code:n";
	getline(cin, msg);
	getline(cin, msg);
}
void Encription() {
	l = msg.size();
	for (j = 0; j < l; j++) {

	}
	for (i = 0; i < l; i++) {

		if (msg.at(i) == ' ') {
			cout << " ";
		}
		else {
			int x = distance(base, find(base, base + 26, msg.at(i)));
			n1 = rotor1[x];
			n2 = rotor2[n1];
			n3 = rotor3[n2];
			n4 = reflec[n3];
			n3 = distance(rotor3, find(rotor3, rotor3 + 26, n4));
			n2 = distance(rotor2, find(rotor2, rotor2 + 26, n3));
			n1 = distance(rotor1, find(rotor1, rotor1 + 26, n2));
			cout << base[n1];

			rII = (i + r2 + 1) % 26;
			rIII = (i + r3 + 1) % 676;

			rotate(rotor1, rotor1 + 1, rotor1 + 26);

			if (rII == 0) {
				rotate(rotor2, rotor2 + 1, rotor2 + 26);
			}
			else {}

			if (rIII == 0) {
				rotate(rotor3, rotor3 + 1, rotor3 + 26);
			}
			else {}
		}
	}
}
int main()
{
	RotorInput();
	RotorInitialization();
	MessageInput();
	Encription();
	cout << endl;
	system("pause");
	return 0;
}

I’m using VS windows, my friend who coded this was using another program, and it worked, but not on mine… I’m going crazy!

  • Ошибка идентификатор cout не определен
  • Ошибка идеального незнакомца сериал 2012
  • Ошибка идеального незнакомца дорама скачать торрент
  • Ошибка идеального незнакомца дорама 2012
  • Ошибка идеального незнакомца cuo dian yuan yang