C++: cin.getline - no instance of overload function - c++

I'am trying to write a line of text to a .txt file, but visual studio 2015 is giving me the following error.
Severity Code Description Project File Line Suppression State
Error (active) no instance of overloaded function "std::basic_istream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits]" matches the argument list Studying c:\Users\Klaas\Documents\Visual Studio 2015\Projects\Studying\Studying\Studying.cpp 16
and
Severity Code Description Project File Line Suppression State
Error C2664 'std::basic_istream> &std::basic_istream>::getline(_Elem *,std::streamsize,_Elem)': cannot convert argument 1 from 'std::string' to 'char *' Studying1 c:\users\klaas\documents\visual studio 2015\projects\studying1\studying1\studying1.cpp 16
My source code:
#include <iostream>
#include "stdafx.h"
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream myFile;
string myText;
myFile.open("sometext.txt");
cout << "Write text to save to file: ";
cin.ignore();
cin.getline(myText, sizeof(myText));
myFile << myText;
myFile.close();
return 0;
}
I have done multiple searches and found answers such as including
cin.ignore();
above the
cin.getline
, but i just can't get it to work and i don't really understand what the error means, and i don't see why it thinks i'm trying to convert a string to char.
Any tips would be very welcome :)

You are not using correct function. Instead of cin.getline() you should use
std::getline(cin, myText)
cin.getline() expects a pre-allocated char*, and your myText is not. It is also very hard to somehow manage to preallocate a buffer long enough for std::basic_istream::getline(), so this function is almost never useful at all.

use getline(cin,myText) I honestly don't know why this problem exists or if it even is a problem but i know for a fact that this works.

See : http://www.cplusplus.com/reference/istream/istream/getline/
See : http://en.cppreference.com/w/cpp/io/basic_istream/getline
The first parameter of this function getline must be a char *, not a string.
char myText[1024];
cin.getline( myText, sizeof(myText) );
As mentioned everywhere else, it's better to use the std::getlinefunction:
http://en.cppreference.com/w/cpp/string/basic_string/getline

Related

Compiling error while using getline(): 'mismatched types'

I keep getting this error (it's a really long one but I think the most important part is this):
main.cpp:9:30: note: mismatched types 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'const char [2]'
While compiling this bit of code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = getline(cin, " ");
return 0;
}
The lines in the error won't match with the ones in the code I brought up here because I don't know how to make a new line whilst writing code in the Stack Overflow editor; I'm new here ;) Anyways, the error points to the line with the declaration of string x.
Basically what I want this code to do is to get a line from the user until he/she hits space. Maybe I'm doing something wrong from the beginning, so I'm open for suggestions of fixing this problem. (I'm not very experienced in C++, it's just that my teacher required to complete a task using this language.) Thanks,
Anthony
The second parameter of std::getline() is a reference to a std::string variable that accepts the read data. The string is not outputted in the function's return value.
Also, std::getline() does not accept a string for the delimiter. It takes only a single character.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string x;
getline(cin, x, ' ');
return 0;
}

ostream .open function not existing (C++)

So I'm new to programming and I'm following a tutorial and I got to fstream, but I don't know if my compiler is acting weirdly or I'm missing a file or something but the .open function does not seem to work and fstream is acting weirdly. (Like you cannot use (ostreamobject)("test.txt"); I'm new to programming so please don't use technical terms.
I've searched around a bit but I didn't find anything.
I don't know what's wrong with my code or my compiler but outputFile.open does not exist weirdly enough. I'm using visual studio 2015. This is a small amount of code I wrote and it still comes with an error. Here's the code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ostream oFile;
istream iFile;
oFile.open("test.txt");
return 0;
}
Here's the error codes:
1>d:\dokument\visual studio 2015\projects\fstream\fstream\fstream.cpp(13): error C2512: 'std::basic_ostream>': no appropriate default constructor available
1> d:\programmering\vc\include\iosfwd(679): note: see declaration of 'std::basic_ostream>'
1>d:\dokument\visual studio 2015\projects\fstream\fstream\fstream.cpp(14): error C2512: 'std::basic_istream>': no appropriate default constructor available
1> d:\programmering\vc\include\iosfwd(678): note: see declaration of 'std::basic_istream>'
1>d:\dokument\visual studio 2015\projects\fstream\fstream\fstream.cpp(16): error C2039: 'open': is not a member of 'std::basic_ostream>'
1> d:\programmering\vc\include\iosfwd(679): note: see declaration of 'std::basic_ostream>'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
The problem is, that you are using "ostream" and "istream" instead of "ofstream" and "ifstream" (note the "f" for "file").
Use this version:
#include "stdafx.h"
// #include <iostream> // you don't need this and it caused most of your confusion!
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream oFile;
ifstream iFile;
oFile.open("test.txt");
return 0;
}
FYI:
"ofstream" and "ifstream" are both superclasses of "ostream" and "istream". They provide further functions (like "open") for interacting with files
Well, it doesn't exist. There is no ostream constructor that takes a filename.
You meant ofstream.
You could have checked this out by simply visiting the documentation.
If your tutorial really says ostream, tell us what it is and stop using it.
You should learn C++ from a good book, not from random "tuts" on the internet.
Consider declaring oFile and iFile as concrete files.
ofstream oFile;
ifstream iFile;

Function cannot be referenced as it is a deleted function

Hello I am learning C++ from a book and am on a exercise question below
Write a function that takes and returns an istream&. The function should read the stream until it hits end-of-file. The function should print what it reads to the standard output. Reset the stream so that it is valid before returning the stream.
#include "stdafx.h"
#include <iostream>
#include <istream>
#include <string>
#include <string.h>
#include <list>
#include <vector>
#include <fstream>
std::istream ReadFile(std::istream &iStream)
{
std::string word;
while (iStream >> word)
{}
std::cout << "I read value " << word << std::endl;
iStream.setstate(std::ios::goodbit);
return iStream;
}
int _tmain(int argc, _TCHAR* argv[])
{
ReadFile(std::cin);
system("pause");
return 0;
}
The above is my attempt, however I am getting errors at the "return iStream" line.
Error1 error C2280: 'std::basic_istream<char,std::char_traits<char>>::basic_istream(const std::basic_istream<char,std::char_traits<char>> &)' : attempting to reference a deleted function
2 IntelliSense: function "std::basic_istream<_Elem, _Traits>::basic_istream(const std::basic_istream<_Elem, _Traits>::_Myt &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 77 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\istream") cannot be referenced -- it is a deleted function
I don't really know what these errors are, I am aware you can delete stuff but I am not onto that topic in the book yet. As far as I know I have not at all touched the istream file... Can someone help me please?
Thanks!
You can’t return an istream by value because it’s not copyable.
Since it’s not copyable the copy constructor has been deleted (to enforce the non-copyability), and that’s the direct technical cause of the diagnostic.
So, instead of
std::istream ReadFile(std::istream &iStream)
… do
std::istream& ReadFile(std::istream& iStream)
In other news, …
Instead of
#include "stdafx.h"
just turn off precompiled headers in the Visual Studio project settings.
This also gives you more standard-conforming behavior for header inclusions.
If you don’t do that, then configure the project so that any warning about skipping an include, yields a hard compilation error.
Instead of
iStream.setstate(std::ios::goodbit);
… do
istream.clear();
Instead of the non-portable Microsoft monstrosity
int _tmain(int argc, _TCHAR* argv[])
just use standard
int main()
or in C++11 trailing return type syntax,
auto main() -> int
Instead of
system("pause");
simply run your program via Ctrl+F5 in Visual Studio. Or, place a breakpoint on the last right brace of main and run in the debugger. Or, run the program from the command line.
The exercise formulation
” should read the stream until it hits end-of-file
is ambiguous, but anyway reading words, as you’re doing, does not faithfully reproduce whitespace in the stream. For a more accurate reproduction of the stream contents you can either read character by character, or (via getline) line by line. Or, you can use a special mechanism for this task, namely outputting the read buffer, which does everything in one little statement.
Finally, you don’t need all those headers. You only need <iostream>, and if you choose to read lines, also <string>. Also, you don’t need the return 0; at the end of main, because that’s the default.
A deleted function is a special function (constructor, destructor, operator) that has been explicitly disabled. If you look carefully at the error you can see that the function is the basic_istream copy-constructor, which is disabled because istreams cannot be copied. You are attempting to copy the istream when you return istream, since your function is declared as returning an istream (rather than e.g. returning a reference to an istream).

Using Strncmp with a string from a file

Goodnight to everyone, I'm trying to parse an .h file so I can have a small console frontend to change its values, but when I try to use strncmp with a string read from a file and a string defined in code to compare with the file string I get a strange error from the compiler that I cant resolve, here is my source code:
//Test to basic file operations
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main (void){
string line;
ifstream myfile("PIDconfig.h");
if(myfile.is_open()){ //if file is open
while(myfile.good()){
getline(myfile, line);
if(strncmp(line, "static float", 12) == 0){
cout << line << endl;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
And the error that I get:
tiago#tiago-laptop:~$ g++ file.cpp
file.cpp: In function ‘int main()’:
file.cpp:17: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int strncmp(const char*, const char*, size_t)’
If some one could help me I would be very glad, I have already searched StackOverflow but I didnt found anyone with the same problem, almost all strncmp problems use arrays to store their strings and as far as I went, no one was having a problem using it and file I/O.
std::string overloads operator==. You can simply compare two std::string object using ==.
Also, your input loop is incorrect.
the problem is that strncmp() function overloaded for strncmp(const char*, const char*, int)
but you want to call it by strncmp(string, string, size_t)
you must convert string to const char* with
c_str()
for example
string str = "Hello";
char * arr = str.c_str().
you get it?
if(strncmp(line.c_str(), "static float", 12) == 0){
should work
The problem is that you're reading data from the file as a C++ string, and the strncmp function works on C style strings. To fix this, you can either extract a raw C style string from the C++ string using .c_str(), or you can use the C++ string's .compare function:
line.compare(0, 12, "static float")

C++ compiler error with stringbuf / ifstream

I cannot understand why my compiler (MSVC++2010) doesn't like this code:
// get_sum(filename as c-string) returns sum from file
int get_sum(const char* const s) {
stringbuf bill_buf;
ifstream bill_file;
bill_file.open(s);
bill_file.get(bill_buf, '\0'); // read whole file
bill_file.close();
return get_sum_from_string(bill_buf.str());
}
I get these errors (I translated them from German to English and give the correct line numbers for the code excerpt without leading comment):
Error 1 error C2079: 'bill_buf' uses undefined class 'std::basic_stringbuf<_Elem,_Traits,_Alloc>' (Line 2)
Error 2 error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::get(_Elem *,std::streamsize)': Conversion of parameter 1 from 'int' to 'char *' not possible (Line 5)
Error 3 error C2228: To the left of ".str" there must be a class/structure/union. (Line 7)
Has anyone got an idea what's going on there? Thanks a lot! (If anyone has got a better idea how to quickly get the whole file contents into a string, I'd also appreciate it)
You're missing an include. Here's your code, this time without using streambuf:
#include<fstream>
#include<string>
#include<iterator>
int get_sum(const char* const s) {
std::ifstream bill_file(s);
std::string contents((std::istreambuf_iterator<char>(bill_file)),
std::istreambuf_iterator<char>());
return get_sum_from_string(contents);
}
For #1, you probably forgot to #include <sstream> and only have a forward declaration from some other header in scope. #2 and #3 are follow-up errors, don't mind them, fix #1 first and go on.
Looks like you need to #include <sstream>.
1) In your header file (.h) you should specify "using namespace std". Otherwise, all your stream operations/variables etc have to start with 'std::'
2) Have you included the right headers? You should add
#include <sstream>