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.
Kislorod1234 0 / 0 / 0 Регистрация: 15.05.2016 Сообщений: 12 |
||||
1 |
||||
02.02.2017, 19:04. Показов 15512. Ответов 4 Метки нет (Все метки)
Ругается на getline , пишет идентификатор не найден
Подскажите в чем проблема
0 |
zss Модератор 13252 / 10392 / 6213 Регистрация: 18.12.2011 Сообщений: 27,798 |
||||
02.02.2017, 19:28 |
2 |
|||
Сообщение было отмечено Kislorod1234 как решение РешениеНету
а cstring Не надо Да, и зачем Вам локализация, если русский текст не используете
1 |
0 / 0 / 0 Регистрация: 15.05.2016 Сообщений: 12 |
|
03.02.2017, 08:35 [ТС] |
3 |
Спасибо. Подскажите можно ли открыть файл для чтения и для записи в конец одновременно? Добавлено через 31 минуту
0 |
Модератор 5151 / 2331 / 339 Регистрация: 20.02.2013 Сообщений: 5,720 Записей в блоге: 20 |
|||||
03.02.2017, 09:19 |
4 |
||||
.
0 |
Модератор 13252 / 10392 / 6213 Регистрация: 18.12.2011 Сообщений: 27,798 |
|
03.02.2017, 09:54 |
5 |
cin.getline(f,str,»); std::getline и istream::getline — это разные функции.
0 |
I have looked at a few other questions regarding getline() not functioning, however most problems regarding the topic were due to the programmer not including the string header. I have the string header included however getline is still giving me error E0304 (which I have already looked into).
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char input[100];
getline(cin, input);
cout << input << endl;
}
asked Jul 27, 2019 at 3:19
2
There are two forms of getline
:
std::cin.getline(array, size); // reads into raw character array
getline(std::cin, string); // reads into std::string
You should use a std::string
instead of a raw character array:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string input;
getline(std::cin, input);
std::cout << input << "n";
}
answered Jul 27, 2019 at 3:32
L. F.L. F.
19.2k8 gold badges46 silver badges80 bronze badges
The non-member getline
only works with std::string
. Use the std::istream
member function getline
for C-style strings:
std::cin.getline(input, sizeof(input));
O’Neil
3,7904 gold badges15 silver badges30 bronze badges
answered Jul 27, 2019 at 3:23
eesiraedeesiraed
4,6264 gold badges16 silver badges34 bronze badges
1
- Remove From My Forums
-
Question
-
My codes are similar to below snippet. I got error of «…error C3861: ‘getline’: identifier not found …».
If I added #include <iostream> and change getline() as std::getline(), I got error:
«‘std::getline’: no matching overloaded function found».
‘std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)’: expects 2 arguments — 3 providedHow should I use getline() correctly? My platform is VS2015.
#include <stdio.h>
#include <stdlib.h>FILE *file
= fopen(filename, "r");.....
//
read each line and print it to the screen
int line_number = 0;
while(-1 != getline(&buffer,
&buffer_size, file))
{
printf("%d: %s",
++line_number, buffer);
}
-
Edited by
Monday, August 21, 2017 6:25 AM
-
Edited by
Answers
-
Hello,
use the std-lib like this:
#include <fstream> CString szFilename = _T(" <your filename> "); std::ifstream fi; fi.open((LPCTSTR)szFilename); if (!fi.is_open()) { return; } char szline[10240]; while (fi.getline(szline, 10240)) { // ... } fi.close();
Regards, Guido
-
Edited by
Guido Franzke
Monday, August 21, 2017 7:42 AM -
Marked as answer by
Stan Huang at Taiwan
Tuesday, August 22, 2017 2:57 AM
-
Edited by
-
On 8/21/2017 2:24 AM, Stan Huang at Taiwan wrote:
FILE *file = fopen(filename, «r»);
std::getline is designed to read from std::istream or a class derived therefrom; not from FILE*. And it reads into std::string, not a raw buffer. If you insist on using FILE* and raw buffer, there’s fread(). Otherwise:
std::ifstream file(filename); std::string line; int line_number = 0; while (std::getline(file, line)) { std::cout << ++line_number << ": " << line; }
-
Marked as answer by
Stan Huang at Taiwan
Tuesday, August 22, 2017 3:30 AM
-
Marked as answer by
-
How should I use getline() correctly? My platform is VS2015.
#include <stdio.h>
#include <stdlib.h>FILE *file
= fopen(filename, "r");.....
//
read each line and print it to the screen
int line_number = 0;
while(-1 != getline(&buffer,
&buffer_size, file))
{
printf("%d: %s",
++line_number, buffer);
}
By way of fleshing out some of the details, take note that there are
two getline() functions:(1) istream::getline
https://msdn.microsoft.com/en-us/library/aa277361(v=vs.60).aspxThis is a member function of basic_istrean and its derivatives.
It reads the string into a «raw» or «native» character array.
The reply from Guido uses this version of getline.(2) std::getline (from <string>)
https://msdn.microsoft.com/en-CA/library/2whx1zkx(v=vs.100).aspx
https://msdn.microsoft.com/library/1a4ffd11-dce5-4cc6-a043-b95de034c7c4.aspx#getline_template_functionUnlike (1) above, this is not a member function of a class.
It reads the string into a std::string.
The reply from Igor uses this version of getline.As noted by Igor, if you must use the input streams from the C Standard
Library (fopen, FILE*) then the preferred route would be to use the
functions provided for manipulating such streams. To read strings, see:fgets, fgetws
https://msdn.microsoft.com/en-us/library/c37dh6kf.aspx— Wayne
-
Marked as answer by
Stan Huang at Taiwan
Tuesday, August 22, 2017 3:36 AM
-
Marked as answer by
-
On 8/21/2017 11:33 PM, Stan Huang at Taiwan wrote:
It works basically. But why the line «
<p>std::cout << ++line_number << <span style="margin:0px; padding:0px; border:0px; vertical-align:baseline; color:#a31515">": "</span> << line;"</p><p></p><p>I got error of</p>«error C2039: ‘cout’: is not a member of ‘std'»
You are probably missing #include <iostream>
-
Marked as answer by
Stan Huang at Taiwan
Tuesday, August 22, 2017 4:12 AM
-
Marked as answer by
-
I learned the usage of getline() form http://timmurphy.org/2010/10/31/reading-from-a-file-in-c-2/
I guessed it worked at some situation. So, how come it doesn’t work at VS environment?
That uses a non-standard C extension that is supported by some compilers
on some platforms. It is not part of the ISO C99 Standard nor the ISO
C++ Standard, and is not supported by Visual C++. See:undefined reference to `getline’ in c
https://stackoverflow.com/questions/13112784/undefined-reference-to-getline-in-c— Wayne
-
Marked as answer by
Stan Huang at Taiwan
Tuesday, August 22, 2017 5:23 AM
-
Marked as answer by
getline error
I’ve been fiddling with the cin and getline functions lately, but I haven’t wrapped my head on why this piece of code doesn’t work. I combined my code starting from another tutorial I’ve done just recently, but for some reason if I were to use the getline function for what I’m trying to do below, it would just skip to the next cout function instead of telling me to input something. Here is the code:
|
|
Once all the integers are input, the last cout functions that ask for the name go through without letting me input my string. However, after messing around with the sample coding I realized something: Placing a getline function with a string doesn’t work, but if another getline function were to be placed again, then the code will function as should be. This is the final code with the solution:
|
|
Now I did solve my problem. But I know that there’s a better way of doing this. Can anyone tell me what I did wrong with my initial code and why the getline function doesn’t work? This only fails whenever I have to input integers though. Whenever I put the string input section to the top of the code, it would work just fine.
When you input an integer, or other value using the extraction operator >>
, the input process stops at the first whitespace or non-numeric character. Any unprocessed characters remain in the input buffer. That includes the newline character ‘n’ which was entered from the keyboard after the data.
If you then do a getline() operation, it will process everything up to the first newline character. The newline itself is discarded. Hence it will get the remnants of the previous input, which is an empty line.
You could either do the getline and ignore the result, or use the cin.ignore() function with a delimiter of ‘n’.
Yeah you have to clear the buffer before using the getline or cin since the search for the newline and whitespace characters respectively by default.
So something like:
|
|
HTH,
Aceix
That fixed the issue. Chervil, I still don’t quite understand the idea behind the process of the buffer…Do you mean that the getline process takes the newline and jumps to the next cout function?
The buffer is a block of memory where the input from the keyboard (or other stream, such as a file) is temporarily stored.
Lets say you want to input an integer.
cin >> number;
The user enters a number, and presses [enter]. The buffer looks like this: "34n"
When the cin
statement reads the contents of the buffer, it stops at the last numeric character. Thus, the buffer afterwards looks like this: "n"
.
If the program now has a getline statement, getline (cin, mystr);
it will read the contents of the buffer, up to and including the ‘n’ character. The string mystr contains ""
(an empty string) and the newline is discarded. Processing continues at the next statement.
Lets try that same process again, with different input.
The user enters a number, and may deliberately or accidentally type some other characters, and presses [enter].
cin >> number;
The user enters " 34 asdfg n"
.
The cin statement ignores the leading whitespace, accepts the numeric values as the integer, and leaves the remaining characters in the buffer.
Afterwards, the buffer looks like this: " asdfg n"
.
Now, the getline statement will again take everything up to the newline.
The string mystr contains " asdfg "
.
|
|
The main point is that getting an integer or other variable using cin >> variable;
reads just enough from the input buffer to satisfy the request. Anything else will remain in the buffer, including the newline character.
The getline()
command is in some ways more straightforward, it reads everything up to and including the newline. The newline itself is not stored, but it is removed from the buffer.
Try the above program with line 17 re-instated (currently commented out).
Last edited on
I understand now. If I can comprehend correctly, the parameters of cin.ignore clears out 1000 characters or up until the new line correct?
What does simply doing cin.ignore() do then? Also, I’m sort of confused on the use of «::» (I guess since I’m still looking at tutorials I wouldn’t understand it yet) for these functions. Is it another way of declaring them?
What does simply doing cin.ignore() do then?
Take a look at the reference for ignore(), http://www.cplusplus.com/reference/istream/istream/ignore/
If you call it with no parameters, it will use the default parameters.
That is, it will ignore at most one character, until the EOF value is met. Generally, EOF is relevant to files, rather than keyboard input.
So it’s roughly correct to say it will ignore just one character.
Learn about default parameters here:
http://www.cplusplus.com/doc/tutorial/functions2/
Also, I’m sort of confused on the use of «::»
The ::
is the scope resolution operator.
It’s used when a name belongs to a particular class or namespace. In C++ the standard libraries such as <iostream> and so on belong to the std
namespace.
There are three common ways to handle this.
1. put using namespace std;
at the top of the program. This is often done in example programs, but despite that, it is not regarded as good practice.
2. put individual using statements for each of the required items from the particular namepace.
|
|
3. Explicitly specify the full name on every usage of such items, for example:
|
|
The third method is considered the safest, as there is no ambiguity over which name is intended to be used.
Last edited on
Would it be best to use the second or third method in handling code? How does using using namespace std;
considered a bad practice?
When you put using namespace std;
, it brings all of the items from the standard namepace into your program (depending on which #includes you have).
That is bad as it defeats the whole purpose of having separate namespaces in the first place. It increases the likelihood of naming conflicts between code you write yourself, and code in the standard library.
Which way would be best to use out of methods 2 and 3? I would consider 3 since it’s the safest though I would like to use 2 as well.
Topic archived. No new replies allowed.