C++ how do i use a variable for ifstream [duplicate] - c++

This question already has an answer here:
No matching function - ifstream open()
(1 answer)
Closed 7 years ago.
void searchString(const string selection,const string filename)
{
ifstream myfile;
string sline;
string sdata;
myfile.open(filename);
while(!myfile.eof())
{
getline(myfile,sline);
sdata = sdata + sline;
}
How do i use string filename as myfile.open(filename)
Initially i was using file.txt instead, but if i use a variable that pass in by the function, like string filename, it give me an error
myfile.open("file.txt");
Error message is as followed:
main.cpp:203:25: error: no matching function for call to ‘std::basic_ifstream<char>::open(const string&)’
main.cpp:203:25: note: candidate is:
/usr/include/c++/4.6/fstream:531:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode]
/usr/include/c++/4.6/fstream:531:7: note: no known conversion for argument 1 from ‘const string {aka const std::basic_string<char>}’ to ‘const char*’
make: *** [main.o] Error 1

The constructor for std::ifstream::open (for the particular standard of C++ that you're using) doesn't allow a std::string argument, so you have to use:
myfile.open(filename.c_str());
The constructor expects type const char * which you can obtain from a std::string object using its c_str() member function.

Related

To read fileName as commandLine argument and perform file Operation "open" in c++98 Linux

I am reading abc.cpp file which is placed under /home/documents/abc.cpp. To open file I am performing file operation open("t.open("/home/documents/abc.cpp"). where i am able to perform open operation on file.
I want to try to read file name using command line argument. so what i am trying here is in command line
./a.out abc.cpp , passing argv[1] as file name and concatenate string path + argv[1], when i compile the code i will thrown with compilation errors, how to solve this issue please help.
#include <iostream>
#include <fstream>
#include <sstream>
#include<string.h>
#include <ext/stdio_filebuf.h>
using namespace std;
int main(int argc, char *argv[])
{
ifstream t;
string path = "/home/documents/";
string file = path + argv[1];
t.open(file);
//t.open("/home/documents/abc.cpp");
string buffer;
string line;
while(t)
{
getline(t, line);
// ... Append line to buffer and go on
buffer += line;
buffer += "\n";
}
t.close();
return 0;
}
compilation error
g++ cmdLine.cpp
cmdLine.cpp: In function ‘int main(int, char**)’:
cmdLine.cpp:13:32: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::string&)’
t.open(file);
^
cmdLine.cpp:13:32: note: candidate is:
In file included from cmdLine.cpp:2:0:
/usr/include/c++/4.8.2/fstream:538:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
open(const char* __s, ios_base::openmode __mode = ios_base::in)
^
/usr/include/c++/4.8.2/fstream:538:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
t.open(file.c_str()); will solve your problem. Until C++11 the only function declaration was
void open( const char *filename,
ios_base::openmode mode = ios_base::in );
The error message informs you very clearly: no known conversion from ‘std::string’ to ‘const char*’.

Long, nearly incoherent errors C++

Sometimes I get incredibly long errors in my code that I don't understand so I just rework my code to avoid whatever was causing the error. I had another one today that I simply can't avoid.
My code:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
void readFile(string);
class info {
public:
int rows;
int cols;
vector < string > data;
};
int main(int argc, char **argv){
string filename1;
filename = argv[1];
readFile(filename);
return 0;
}
//should read onle line at a time from a file and print it
void readFile(string filename1){
fstream datafile;
datafile.open(filename1);
while (!datafile.eof()){
string line;
getline(datafile,line);
cout<<line<<endl;
}
datafile.close();
}
The error stems from trying to get the name of the file from argv[1]. It was working fine when I just gave it the file name.
The error:
project2.cpp: In function ‘int main(int, char**)’:
project2.cpp:22:2: error: ‘filename’ was not declared in this scope
filename = argv[1];
^
project2.cpp: In function ‘void readFile(std::string)’:
project2.cpp:32:25: error: no matching function for call to ‘std::basic_fstream<char>::open(std::string&)’
datafile.open(filename1);
^
project2.cpp:32:25: note: candidate is:
In file included from project2.cpp:2:0:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/include/c++/fstream:889:7: note: void std::basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
open(const char* __s,
^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.3/include/c++/fstream:889:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
I am using Cygwin. I used it last semester as well when I was writing code in C, and my professor had us check certain installation options at the time. Could these installation options be the root of the problem? Or are errors like this common in C++? Thanks.
Just read the error:
project2.cpp: In function ‘int main(int, char**)’: project2.cpp:22:2:
error: ‘filename’ was not declared in this scope filename = argv[1];
^
Here it says that filename is not declared. i.e. You have to declare it or something wrong with the declaration
Looking at the code you have
string filename1;
One assumes you meant
string filename;
Fix this error - then try again
The first error:change filename1 to filename
The second error: you should set a open()functions in the class info.then you can use it

String c++ manipulation

Why the following code have compilation error?
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="abc";
string result=str[0];
cout<<result<<endl;
return 0;
}
However, the following code works fine:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="abc";
str=str[0];
cout<<str<<endl;
return 0;
}
I works in unix and compilation command is: "g++ -g test.cpp -std=c++11 -o a", thenm ./a
The error for the first test.cpp after compile is:
test.cpp:9:21: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
string result=str[0];
^
In file included from /usr/um/gcc-4.8.2/include/c++/4.8.2/string:52:0,
from /usr/um/gcc-4.8.2/include/c++/4.8.2/bits/locale_classes.h:40,
from /usr/um/gcc-4.8.2/include/c++/4.8.2/bits/ios_base.h:41,
from /usr/um/gcc-4.8.2/include/c++/4.8.2/ios:42,
from /usr/um/gcc-4.8.2/include/c++/4.8.2/ostream:38,
from /usr/um/gcc-4.8.2/include/c++/4.8.2/iostream:39,
from test.cpp:1:
/usr/um/gcc-4.8.2/include/c++/4.8.2/bits/basic_string.h:490:7: error: initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' [-fpermissive]
basic_string(const _CharT* __s, const _Alloc& __a = _Alloc());
^
std::basic_string doesn't have any constructor that takes a single CharT argument. This means that std::string (i.e. std::basic_string<char>) cannot be constructed from a single char.
The class does, however, have an assignment operator overload that takes a single CharT argument, which is why your second example compiles.
The difference between the two cases is because in the first you're performing copy initialization, which means technically you're first attempting to construct a temporary std::string instance from the char argument, and then copy it over to result. In the second you're performing assignment, which means assigning a new value to an existing std::string instance.
basic_string does have a constructor that takes a count followed by a character:
basic_string(size_type count, CharT ch, const Allocator& alloc = Allocator());
so your original example would compile if you changed the offending line to
string result = {1, str[0]};
The following code works fine as well:
string result;
result=str[0];
That means the difference is between initialization and simple assignment and, if you examine the error:
error: invalid conversion from ‘char’ to ‘const char*’
it should be clear that the initialization is not as "full-featured" as assignment - the is no string constructor that takes a char argument (there is an assignment that takes a char which is why your second example works).
You can fix it (in one way, there's no doubt others as well) by ensuring you initialize with a string rather than a character:
string result = str.substr(0,1);
str[0] returns a char&, but there is no conversion from char& to std::string
try thins instead
string result = string(1, str[0]);

g++ ifstream matching error

void FileIO :: openFile(const char* m_FileName,const char* m_FileMode);
I am getting error:
FileIO.cpp: In static member function ‘static void FileIO::openFile(const char*, const char*)’:
FileIO.cpp:12:45: error: no matching function for call to ‘std::basic_ifstream<char>::open(const char*&, const char*&)’
FileIO.cpp:12:45: note: candidate is:
In file included from FileIO.h:1:0:
/usr/include/c++/4.7/fstream:531:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
/usr/include/c++/4.7/fstream:531:7: note: no known conversion for argument 2 from ‘const char*’ to ‘std::ios_base::openmode {aka std::_Ios_Openmode}’
std::basic_ofstream::open doesn't take two const char*s. (note: your subject says ofstream but from your comments it appears you're talking about ifstream).
http://en.cppreference.com/w/cpp/io/basic_ifstream/open
void open( const char *filename,
ios_base::openmode mode = ios_base::in );
void open( const std::string &filename,
ios_base::openmode mode = ios_base::in ); (since C++11)
The problem is the second, not the first argument.
ifstream ifs;
ifs.open("hello", "rb" /*<-- problem, this is a const char* not flags.*/);
Instead, you need to pass it std::ios_base flags
ifstream ifs("hello", std::ios_base::in | std::ios_base::binary);
or
ifstream ifs;
ifs.open("hello", std::ios_base::in | std::ios_base::binary);
--- EDIT ---
Looking at your comments following the post (why didn't you edit the post?) you are also trying to check for 'NULL'.
In C and C++ 'NULL' is a macro which is #defined as 0. So, checking for NULL can check for a null pointer, but it also can test for numeric values. If you want to check if the file opened, you will need to do:
m_FileInput.open("hello", std::ios_base::in | std::ios_base::binary);
if (!m_FileInput.good()) // checks if the file opened.
And you should try to use 'nullptr' instead of 'NULL' when possible.
You're trying to use C's FILE* syntax to call a C++ open function. The mode (read/write/append) arguments are NOT string literals in C++ but enumerated values possibly ORed together.

Reading text from several files C++

I have some text files in a folder named foo1, foo2,...,foo5. I tried to write a C++ program
to print out the contents of the files but the compiler is giving an error.
Here is the program.
int main(int argc, char *argv[])
{
string common="foo";
for(int count=1;count<=5;++count)
{
//Convert count to an string.
stringstream ss;
ss<<count;
string numstring=ss.str();
string filename=common+numstring;
ifstream infile(filename);
string line;
//Print out the lines from the file.
while(getline(infile,line))
{
cout<<line<<endl;
}
}
return 0;
}
The compiler is giving an error like
g++ -Wall c++.cpp
c++.cpp: In function ‘int main(int, char**)’:
c++.cpp:26: error: no matching function for call to ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)’
/usr/include/c++/4.4/fstream:454: note: candidates are: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.4/fstream:440: note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.4/iosfwd:81: note: std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)
Can someone help me out with this? The output of the program should be what I would get if I typed cat foo* at the terminal.
Replace:
ifstream infile(filename);
with
ifstream infile(filename.c_str());
The error message that you posted shows you this. fstream is a typedef for basic_fstream<>. Your error message says, in essence, that there is no fstream constructor that takes a string&, but there is one that takes a char*.
You can't do this:
ifstream infile(filename);
The ifstream class doesn't know how to take a string as a filename. I does know how to take a character array:
ifstream infile(filename.c_str());
You should have worked this out with a single input file, before you introduced the iteration. Start simple and build up. Test all the way. Never add to code that doesn't work.