C++ compiler error with stringbuf / ifstream - c++

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>

Related

Insertion operator is not working with vector and I don't know why

So I was starting to write my code and I was going to test to see if I still remember how to cast, until I get a red line under my operator.
This is the compiler error:
Error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' (or there is no acceptable conversion) (12)
I honestly never had a problem with outputting a string/vector so I do not know how to fix this. Can someone please tell me how to fix this. It would also be awesome if you could tell me what is wrong with the code.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string>hello;
hello.push_back("9");
for (auto i : hello)
cout << i << " "; <-- The first operator is underlined. Why?
return 0;
}
You need one more include in your program:
#include <string>
While <iostream> does declare/define some string related functions, not all of them.
With some compilers, the iostream header incldues string internally, but that isn't required by the standard - and Visual Studio doesn't, that's why you receive this error.

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

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

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).

Converting a string to float using std::istringsteam in C++

I've been trying to convert a simple string to a float, but I'm having no luck with it. this is what I've got at the moment:
int main()
{
float value;
std::string stringNum = "0.5";
std::istringstream(stringNum) >> value;
return 0
}
but I'm getting this error:
Error 2 error C2440: '<function-style-cast>' : cannot convert from 'std::string' to 'std::istringstream' c:\users\administrator\desktop\Test\main.cpp 12
can anyone give me some guidance here on how to just simply convert the string to a float?
Thanks
Most likely you haven't included all the relevant headers:
#include <string>
#include <sstream>
Here is a live example showing that your code compiles when the appropriate headers are included.
In general, you should not rely on indirect inclusion of a necessary standard header file from another standard header file (unless, of course, this inclusion is documented in the Standard itself).
Also notice, that you are creating a temporary string stream, which will be destroyed at then end of the evaluation of the expression
std::istringstream(stringNum) >> value
You may want to create a stream object this way instead:
std::istringstream ss(stringNum);
ss >> value;
// Here you can use ss again...

C++: Trouble Using String as Argument of a Function

Okay, I am having trouble with the following piece of code (in a header file):
#ifndef XML_H_INCLUDED
#define XML_H_INCLUDED
#include "libxml/parser.h"
#include "libxml/xmlwriter.h"
#include <string>
class XmlFile{
public:
XmlFile(string filename){
file = xmlParseFile(filename);
}
xmlDocPtr file; //Pointer to xml file
};
#endif // XML_H_INCLUDED
The file is including in the main source file (but is not accessed, so its contents are not important).
I keep getting the following error (In Codeblocks):
error: cannot convert 'std::string' to 'const char*'
for argument '1' to 'xmlDoc* xmlParseFile(const char*)'|
I have run into this many times, and it is driving me crazy.
I would prefer not to use vectors if possible (adds another step in initializing the function.
What am I doing wrong? I've tried looking this up, but have not found any satisfactory answers.
Thanks in advance.
file = xmlParseFile(filename.c_str());