Strings as File names - c++

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.

Related

Is there any way to convert string characters into integer? [duplicate]

I am trying to take a string and parse it into an int. I have read the many answers out there, and it seems that using stoi is the most up-to-date way. It appears to me that stoi uses std, but I am getting Function 'stoi' could not be resolved despitre using namespace std;
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include<stdlib.h>
using namespace std;
int main(int argc, char* argv[]) {
string line = "";
string five = "5";
int number = stoi(five); //Error here with stoi
return 0;
}
Any ideas what is causing this?
Update:
I am using Eclipse. My flags are: -c -fmessage-length=0 -std=c++11
If you are using GCC or MINGW, then this is the answer:
std::stoi doesn't exist in g++ 4.6.1 on MinGW
This is a result of a non-standard declaration of vswprintf on
Windows. The GNU Standard Library defines
_GLIBCXX_HAVE_BROKEN_VSWPRINTF on this platform, which in turn disables the conversion functions you're attempting to use. You can
read more about this issue and macro here:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37522.
If you're willing to modify the header files distributed with MinGW,
you may be able to work around this by removing the
!defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF) macro on line 2754 of
.../lib/gcc/mingw32/4.6.1/include/c++/bits/basic_string.h, and adding
it back around lines 2905 to 2965 (the lines that reference
std::vswprintf). You won't be able to use the std::to_wstring
functions, but many of the other conversion functions should be
available.
Please always provide platform and compiler information.
Toggle on C++11 support in your compiler flags. -std=c++11 for a recent gcc. For Eclipse, please refer to the corresponding question in the FAQ and this answer explains how to get rid of the remaining Eclipse warning.
If you are amenable to parsing an int another way, how about using an STL algorithm and a C++11 lambda expression?
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "12345";
int num = 0;
for_each(str.begin(), str.end(), [&num](char c){ num = 10 * num + (c - '0'); });
cout << str << " = " << num << endl;
}

When to include the <string> header in your program?

Do you include the "string" header when a library such as "iostream" already provides a solution?
Example: Do you include the string library if you have already included the iostream library? Which is the right professional method?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("input.txt");
string data;
fin >> data;
cout << data << endl; // Works with <iostream>, and without <string>
fin.close();
return 0;
}
Example 2: Use string library if another library provides functionality, even if program compiles without string?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("input.txt");
string data;
fin >> data;
cout << data << endl; // Even though <iostream> allowed program to compile, we include the <string> library.
fin.close();
return 0;
}
Received points off my CSC 101 class programming assignment because even though program worked, teacher said when using the string datatype I needed to include the string library. Even though technically it was fine without it possibly. Thats the question.
Your teacher was correct.
Your program worked without <string> by chance. Your standard library implementation, of that version, on that platform, under those circumstances, on that day, transitively included what you needed via <iostream>. The standard library is just code, like yours, and it just so happens that your particular implementation contains, inside <iostream>, an #include <string>. It could be buried behind many other #includes but got there eventually. But that's honestly pure chance, and does not mean that this is something the language guarantees, or something that must always be the case even in practice.
You should always code to standards.
If you're using features from <string>, include <string>.
Just today I was trying to build my big project with a new toolchain and found a few places where I'd accidentally relied on transitive includes, and it broke the build as a result because the new standard library implementation had a slightly different arrangement of headers. I dutifully added the missing #includes and now the world is a better place for it.

C++ program gives a run-time error when strings are used

#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
string st = "Hello world";
return 0;
}
and
#include <string>
int main ()
{
std::string st = "Hello world";
return 0;
}
I tried compiling this code using minGW compiler on netbeans. It brings up the following error after the successful build.
RUN FAILED (exit value -1,073,741,511, total time: 93ms)
But it works clean when strings are not used. I would like to know what I am doing wrong here. Thanks in advance.
Use c++ strings and don't use using namespace std:
#include <string> //c++ string header
int main ()
{
std::string st = "Hello world";
return 0;
}
#include <string.h> is the old C-style string header and most likely isn't what you want to use here. See this question for more details: Difference between <string> and <string.h>?
Note: If you really wanted the old C-style strings then you really should be using #include <cstring> because this will put those functions into the std namespace and won't cause any namespace pollution that can lead to other undesirable outcomes.
Likely what happened was that you used the old style string header and didn't properly initialize those strings. The old C-style strings don't have a constructor and operator= defined like the std::string class.
Edit: After looking at the Netbeans forum this is a problem with Netbeans and not a c++ issue. Try changing the output to an external terminal in Netbeans. Or run the program directly from the command line. If these approaches don't fix the problem or are undesirable then make a post over on the Netbeans forum. Also have a look at this question: Program won't run in NetBeans, but runs on the command line!
Uss #include <string> instead of string.h

C++ using fstream

Ok so I haven't used C++ since highschool (used to work in borland C++)
Now I want to solve a problem in C++, yet I don't understand why fstream doesn't work
For some reason ios::in doesn't work.
#include <fstream>
fstream f("Cities.txt,ios::in);
How do I use Fstream properly?
Thanks in advance!
Note : I'm using Visual Studio 2008
change from
fstream f("Cities.txt,ios::in);
to
std::fstream f("Cities.txt" , std::ios::in);
^^^ ^ ^^^
namespace you miss" namespace
done!
What you have learned in your highschool probably was way before C++ was standardized in '97. As per the standard, all C++ library functions are part of the std namespace. In order to use fstream which is part of the standard namespace, you have to qualify it with std:: so, that makes your syntax as
#include <fstream>
std::fstream f("Cities.txt",std::ios::in);
As an alternative to std::fstream, consider std::ifstream (and std::ofstream):
#include <fstream>
…
std::ifstream f("Cities.txt");
std::ofstream o("output.txt");
std::string s;
while( f >> s )
o << s;
Personally, I find this more convenient than specifying the open mode.
You have to first create an object of ifstream class and then open the file.
Do it this way.
#include <fstream>
std :: ifstream f ("Cities.txt",ios::in) ;
Then check whether it is open and start working with it.
You are also missing the " after file name.
You can also write
#include <fstream>
using namespace std;
fstream f("Cities.txt",ios::in);
The using directive allows you to not write std:: before everything. Beware, it might be bad practice, but in small programs it should not be an issue.

Differences in reading file using ifstream in g++ and msvc

When using ifstream class to read words from an input file, I have used the following expression:
#include <iostream>
#include <fstream>
int main(int argc, char *argv[])
{
std::ifstream inputStream(myFile.txt);
std::string myString;
myFile.open()
while(myFile.good())
{
myFile >> myString;
printf("%s \n", myString);
}
return 0;
}
The contents of myFile.txt are:
" This is a simple program. "
The compiles and executes as expected using g++ compiler.
However, the same code when compiled using msvc 2008, returns error at the extraction operator (>>) requiring me to replace the std::string with either an initialized character array or any of the supported native types.
This threw me off as I was expecting the usage of the standard library to be same across implementations.
I understand the compile error and know the way to fix it via using c_str().
But, it would help me a great deal, if someone could clarify why the usage for the standard library is different across platforms.
To me it is not starndard anymore !!
EDIT: Code updated to be complete. Content of myFile.txt updated.
Chances are that you forgot to #include <string>. Without it, Microsoft's version of <iostream> (and such) include enough of a declaration of std::string for some things to work, but other parts are missing, so you get strange, seemingly inexplicable failures.
One of the things that's missing is most of the operator overloads for std::string, which is exactly what you seem to be missing.
As an aside, while (myfile.good()) ... is pretty much a guaranteed bug -- you probably want:
while (myfile>>myString)
std::cout << myString << " \n";
Alternatively, you could do the job with a standard algorithm:
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <iostream>
int main() {
std::ifstream myfile("input.txt");
std::copy(std::istream_iterator<std::string>(myfile),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " \n"));
return 0;
}
The following compiles fine for me on MSVC 2010:
std::ifstream inputStream;
std::string myString;
inputStream.open("myFile.txt", std::ifstream::in);
while(inputStream.good())
{
inputStream >> myString;
}
Note: without using std::ifstream::in as my open mode, I got the same error as you. I suggest you check what value you have for this parameter.