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;
Related
If I set a string as a filename, it doesn't work and I have no idea why. (I'm using codeblocks and it seems to work on other IDEs)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string FileName="Test.txt";
ofstream File;
File.open(FileName);
}
This does not work,while this next one does:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream File;
File.open("Test.txt");
}
Error message:
no matching function for call to std::basic_ofstream::open(std::string&)
Can someone help a bit with this problem, I cannot understand why this error occurs.
Due to what should be considered a historical accident in the early era of C++ standardisation, C++ file streams originally didn't support std::string for filename parameters, only char pointers.
That's why something like File.open(FileName), with FileName being a std::string, didn't work and had to written as File.open(FileName.c_str()).
File.open("Test.txt") always worked because of the usual array conversion rules which allow the "Test.txt" array to be treated like a pointer to its first element.
C++11 fixed the File.open(FileName) problem by adding std::string overloads.
If your compiler doesn't support C++11, then perhaps you should get a newer one. Or perhaps it does support C++11 and you just have to turn on the support with a flag like -std=c++11.
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.
So I'm learning to use a class .h and .cpp files in my program that reads a file containing information about a bank account. Initially the code worked fine, however after creating the .h and .cpp class files, things don't work so smoothly anymore, as I'm getting strange errors that don't make sense to me.
This is my MAIN cpp file:
#include "Bankaccount.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{ string fileName;
cout << "Enter the name of the data file: ";
cin>>fileName;
cout<<endl;
bankAccount object(fileName);
return 0;
}
This is my Bankaccount.h file
#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <iostream>
#include <fstream>
#include <string>
class bankAccount
{
public:
bankAccount(string n);
bankAccount();
private:
ifstream sourceFile;
}
And lastly this is the Bankaccount.cpp file
#include "Bankaccount.h"
#include <iostream>
#include <fstream>
#include <string>
bankAccount::bankAccount(string n)
{
sourceFile.open(n.c_str());
}
Which is now generating these errors:
include\Bankaccount.h|13|error: expected ')' before 'n'|
include\Bankaccount.h|18|error: 'ifstream' does not name a type|
include\Bankaccount.h|14|note: bankAccount::bankAccount()|
include\Bankaccount.h|14|note: candidate expects 0 arguments, 1 provided|
include\Bankaccount.h|4|note: bankAccount::bankAccount(const bankAccount&)|
include\Bankaccount.h|4|note: no known conversion for argument 1 from 'std::string {aka std::basic_string}' to 'const bankAccount&'|
I think it might be an issue with the headers? I went a little bit crazy and put all of my relevant headers on each file trying to get it to work.
using namespace std;
This is considered a bad programming practice, and you will do yourself a favor if you forget that this is actually a part of C++ language. Although there are proper situations where one would employ using namespace, this should be avoided until one has a much better technical understanding of C++, its structure, and its grammar; in order to recognize and understand when this can be used correctly (if at all).
In your main() you have:
string fileName;
There is no such class in the C++ library whose name is string. The class's correct name is std::string; however by shoving using namespace std; a few lines above, you end up blissfully unaware of this basic, fundamental fact.
Now, after you understand this, let's go back and look at your header file:
ifstream sourceFile;
Well, there's no such class in the C++ library called ifstream, either. The class's proper name is std::ifstream. All classes and templates from the C++ library exist in the std namespace.
However, because when you #included the header file your using namespace std; alias is not yet defined, your compiler doesn't recognize the class name, and you get this compilation error as a reward.
The solution is not to cram a using namespace std; in your header file. That will simply lead to more chaos and confusion. The proper fix is:
Remove using namespace std; from your code, completely.
Use full names of all classes from the C++ library, everywhere. Replace all references to string, ifstream, and everything else, with their actual class names: std::string, std::ifstream, and so on. Get into the habit of explicitly using the std namespace prefix every time. It might seem like a bother at first, but you'll quickly pick up the habit before long, and you won't think of it twice.
And you'll never be confused by these kinds of compilation errors ever agin.
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
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).