trying to give a variable to ifstream in c++ [duplicate] - c++

This question already has answers here:
Put A String In A ifstream Method [duplicate]
(2 answers)
No matching function - ifstream open()
(1 answer)
Closed 3 years ago.
im new to c++ and trying to put a variable in this line : ifstream studentPaper(paper);
ill pass paper to this function and want to use it there. string paper has my files location (/name/file.txt)
if i put my file name there i dont get any errors = ifstream studentPaper("/name/file.txt");
but when i save my files location in to a string and give string to it ill get error = ifstream studentPaper(paper);
how can i do that without getting errors
void matchGrades(string paper) {
string aa= "asd";
ifstream studentPaper(paper);
ifstream base("base.txt");
int grade=3;
while ((!studentPaper.eof()) && (!base.eof())) {
string l1,l2;
getline(studentPaper,l1);
getline(base,l2);
if(l1==l2){
grade += 3;
} else {
grade -= 3;
}
}
studentPaper.close();
base.close();
cout << grade;

I think that You have to use removed string parameter "/name/file.txt" because parameter split space.

Try doing ifstream studentPaper(paper.c_str()).
Also if your file is located where your main.cpp is you won't need to specify the path. Something like this:
string studentFile = "student_file.txt";
Based on the information provided. If you are still getting an error please post it so that I can adjust my answer.

Related

Unhandled exception when using getline [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 4 years ago.
I keep getting the Unhandled exception when I try to get the first letter after using getline function.
Error:
Unhandled exception at 0x7535DB52 in Lab2 - Containers and Regex.exe:
Microsoft C++ exception: std::out_of_range at memory location
0x00B5F43C.
class CodeMap
{
private:
vector<string> code;
vector<char> character;
public:
CodeMap() { character.resize(11000); }
~CodeMap() {};
void setChar(string filename)
{
string fileName = filename;
ifstream fin;
fin.open(fileName.c_str());
string line = " ";
char codeChar;
while (!fin.eof())
{
getline(fin, line);
codeChar = line.at(0); //Unhandled exception, tried to use [] instead, still error.
}
fin.close();
}
I wondered what is going on here.
Anyway to fix this?
Thanks for helping.
As the linked answer says (in the comment by #NeilButterworth), you cannot use the EOF condition to determine if you can do another read, only if the last read "failed". In the code above when getline finally fails (which it will), you'll have an empty line variable, which you then do an access on.
Try to do while(std::getline(fin, line)) { ... instead. That way, when getline fails, you're not using the contents of the (empty) line.

c++ getline putting different parts of a line into variables [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 5 years ago.
For the life of me, I can't seem to figure out how to do this properly.
First, I read a line from a csv file. Lets say, that line has
2992854,BOB,3452,394832
I don't want to read each result into a console like practically every example I've found, I want them to go in order, into these 4 variables:
int time;
string name;
int location;
int point;
Right now, this is my code:
string line;
ifstream inputFile("input.csv");
std::list<Cramista> Cramistas;
while (!inputFile.eof())
{
int time;
string name;
int location;
int point;
std::vector<std::string> stringArray;
std::size_t position = 0, found;
getline(inputFile, line);
while ((found = line.find_first_of(',', position)) != std::string::npos)
{
stringArray.push_back(line.substr(position, found - position));
position = found + 1;
}
time = stoi(stringArray[0]);
name = stringArray[1];
location = stoi(stringArray[2]);
point = stoi(stringArray[3]);
}
UPDATED:
So, with what I have here, I'm able to get the first 3 out of 4 pieces of the line, and put them into an array, which I can then move into variables. Trying to figure out how to get that 4th part.
I've got 2992854, BOB, and 3452 but I don't have 394832.
I mean basically in order to avoid "reading each result into the console" using
cin >> time >> name >> location >> point;
you would have to split the line by commas (assuming it's a string, then convert the non string data to integers.

Analyzing a string for file name format [duplicate]

This question already has answers here:
How to check if string ends with .txt
(12 answers)
Closed 8 years ago.
A file name is being passed down into a function. The string needs to be checked to make sure it ends with ".bmp"
How do i check for that to later open the file?
For example: if a string contains "picture.txt" it will tell the user the string is not in the correct format. If a string contain "picture.bmp" it should accept it for later use of opening the file.
Thanks in advance!
What OS are you using? If it's Windows / Visual C++, you have functions that properly give you the extension given a file name (for example _spiitpath). If you want something portable, you have boost::filesystem to parse out the name.
The reason why you should use these functions instead of trying to cook something up yourself is that there could be corner or edge cases that you didn't consider, thus causing your code to give wrong results.
You can do something like this:
bool hasExtension(const string& filename, const string& extension)
{
size_t fnlen = filename.length();
size_t exlen = extension.length();
if (fnlen < exlen)
return false;
return memcmp(filename.c_str() + fnlen - exlen, extension.c_str(), exlen) == 0;
}
int main()
{
cout << hasExtension("file.txt", ".txt") << endl;
}

string variable to open file [duplicate]

This question already has answers here:
c++: ifstream open problem with passing a string for text file name [duplicate]
(3 answers)
Closed 10 years ago.
My code should open 100 files (and do something with them) with next indexes in path like:
"c:\Naprzeme\NAPRZ100.IN" next one is "c:\Naprzeme\NAPRZ101.IN" and etc. :
for (int as=100;as<159;as++){
ostringstream ss;
ss << as;
string cherk = ss.str();
string supremeCounter = "c:\\Naprzeme\\NAPRZ"+cherk+".IN";
fstream infile(supremeCounter);
//....other code here
}
and fstream infile(supremeCounter) returns error
28 31 C:\Users\talent\Documents\File.cpp [Error] no matching
function for call to 'std::basic_fstream<char>::basic_fstream(std::string&)'
candidates are: //(here some libs)...
fstream infile(supremeCounter.c_str());

Reading delimited files in C++ [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 8 years ago.
What is the best way to read in a tab delimited file in C++ and store each line as a record? I have been looking for an open source library to help with this, but have been unsuccessful so it looks like I will have to write my own.
typedef vector<vector<string> > Rows;
Rows rows;
ifstream input("filename.csv");
char const row_delim = '\n';
char const field_delim = '\t';
for (string row; getline(input, row, row_delim); ) {
rows.push_back(Rows::value_type());
istringstream ss(row);
for (string field; getline(ss, field, field_delim); ) {
rows.back().push_back(field);
}
}
This will get you started. It doesn't do any checking that each row has the same number of fields, allow for escaping field_delim, etc.
There is no problem in using iostreams - you could read each line with getline into string, and then use stringstream on that string to iterate over fields.
There are a few libraries listed in wikipedia's article CSV_application_support.