C++ Read from text file - c++

everybody. I'm having a rough time trying to code this thing, I hope you can give me some advice.
I'm trying to retrieve some parameters from a text file and then append them to a
variable char array and then execute that char array with a pipe, the command is a bash command.
My problem is how to access the file to retrieve the parameters, I've tried with buffers and
string but conversions haven't really helped, here's the basic idea of my code.
Working code if I write the command directly to the code:
#include <string.h>
#include <cstdlib>
#include <cstdio>
char *out[10], line[256], command[] = {"mycommand parameter1 parameter2 ..."};
FILE *fpipe;
fpipe = (FILE*)popen(command,"r")
fgets(line, sizeof line, fpipe)
out[0] = strtok (line, "="); // <--- I'm tokenizing the output.
My approach to read from file:
std::ifstream file("/path/to/file", std::ifstream::in);
//std::filebuf * buffer = file.rdbuf();
char * line = new char[];
//buffer->sgetn (line, lenght);
getline(file, line)
The commented line are things I've tried, there were others but I didn't comment them.
I'm considering port it to C later, but first I want to get it going.
And I haven't really implemented the append code since I can't read the file yet.
Hope you can give me some tips, thanks!

You're on the right track, you just need to use a std::string which is what getline receieves:
std::string line;
std::getline(file, line);
That reads the first line. But if you needed to read the entire contents of the file into line just do:
std::string line;
std::istreambuf_iterator<char> beg = file.rdbuf();
std::istreambuf_iterator<char> end;
line.assign(beg, end);

The std::getline() takes istream and string as arguments.
istream& getline (istream& is, string& str);
Here is the documentation: http://www.cplusplus.com/reference/string/string/getline/

I would advice to do something like :
#include <string>
#include <fstream>
std::istream file("/path/to/file"); //ifstream is only infile
std::string astringpar;
float afloatingpar;
//in this example there is a string and a float in the file
//separated by space, tab or newline
//you can continue/replace with int or other in fonction of the content
while (file >> astringpar >> afloatpar)
{
//here do what you want with the pars
}
ciao
Ice

Related

Converting a text file into std::vector<string>

I want a vector document variable that will look like
document[0] = "I"
document[1] = " "
document[2] = "want"
document[3] = " "
document[4] = "cake"
document[5] = "."
document[6] = "\n"
With the given line in the file "I want cake.\n"
I'm not sure how to go about doing this and everything I found on delimiters will get rid of whitespace or something.
I have an unordered_set of stopwords that I want to remove from a file. The method I have set up will iterate over a vector and remove_if the word is in my stop words.
The goal is to put all the elements in the document vector into a new file without the stop words.
std::vector<string> MakeFileVector(string filename){
//Get the input from the file
std::ifstream input(filename.c_str());
std::vector<string> doc;
string line;
//For each line in the text File
for ( line ; getline( input, line );)
{
//somehow split up each word/space/period/comma/newline char
//and add to the doc vector
//for each word/space/period/comma/newline char
doc.push_back(str)
}
return doc;
}
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
ifstream myfile("textline.txt");
std::vector<std::string> myLines;
std::copy(std::istream_iterator<std::string>(myfile),
std::istream_iterator<std::string>(),
std::back_inserter(myLines));
Here you go!
You can use std::noskipws found here. This will make sure that whitespaces are not skipped when reading from the stream. Alternatively, you can also use std::getline, found here to get the line into your std::string and then do your processing of whitespaces.

How to get program to read a line? C++

I have a data set with headers and data below those headers. How do I get c++ to read the first line of actual data (which starts on the 3rd row) and keep reading until the file ends?
I know you have to use a while loop and '++' on some declared variable, but I'm not sure how to.
Here is a screenshot of the data file: enter image description here
Just read the first line into a dummy variable first before your while loop
How to read line by line or a whole text file at once?
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
std::getline(file, str); // read a line, as dummy read
while (std::getline(file, str)) // keep reading till end of file
{
// Process str
}
}

Read from text file C++ (fname, lname, class, seat number), store and verify

I have a text file of the classlook like this:
FName LName Class SeatNum
FName2 LName2 Class2 SeatNum2
...
and the list goes on.
How to read lines of strings and store them into different variables?
How to combine Class & SeatNum to be an ID (3D-20)?
How to verify for every input name and ID has to be matched?
For example, input > FName LName Class2-SeatNum2 is wrong, please try again.
Your help is greatly appreciated.
Thanks!
Just a note for next time - because you didn't detail the problem, it was hard to figure out what you mean. Anyhow:
in order to do what you asked you need to:
a) read the data from the file
b) split the data based on the character which is between the cells.
In C++, The split string algorithm is in boost - if you dont know what that is, make sure you take a look in here: http://www.boost.org/
Soltion:
I`m modifying various cPlusPlus guides here to fit your purpouse:
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
using namespace std;
vector<string> getData (string filePath) {
vector<string> Cells; // In the end, here we will store each cell's content.
stringstream fileContent(""); // This is a string stream, which will store the database as a string.
ofstream myfile; // the file which the database is in
myfile.open (filePath); // Opening the file
while ( getline (myfile,line) ) // Reading it until it's over
{
fileContent << line; // adding each line to the string
}
split(Cells, fileContent.str(), is_any_of(" "));// Here, insert the char which seperates the cells from each other.
myfile.close()
return Cells; // returning the split string.
}
Hope i helped :)

#include <fstream> visual c++ 2010 not working properly

I know that the title is a little vague but i can't think of a better title right now.
The extract from my code looks like this:
#include<iostream>
#include<fstream>
int main(){
ifstream f("cuvinte.txt");
f.getline(cuvant);
return 0;
}
When i want to read the next word from "cuvinte.txt" i write f.getline(cuvant); but i get the following error
error C2661: 'std::basic_istream<_Elem,_Traits>::getline' : no overloaded function takes 1 arguments
I don't know what the issue is, and i stumbled upon this problem a while ago and still can't get past it.
I don't know what the issue is, and i stumbled upon this problem a
while ago and still can't get past it.
To the reference!
basic_istream& getline( char_type* s, std::streamsize count );
You need to provide the size, i.e. the amount of available space in cuvant.
f.getline(cuvant, size);
^^^^
EDIT
An alternative would be to use more modern instruments:
string cuvant;
getline(f, cuvant);
You seem a little shaky on your familiarity with the various forms of getline. Here are a few simple uses of it for your reference:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
string filepath = "test.txt"; // name of the text file
string buffer; // buffer to catch data in
string firstLine; // the first line of the file will be put here
ifstream fin;
fin.open(filepath); // Open the file
if(fin.is_open()) // If open succeeded
{
// Capture first line directly from file
getline(fin,firstLine,'\n'); // Capture first line from the file.
cout << firstLine << '\n'; // Prove we got it.
fin.seekg(0,ios_base::beg); // Move input pointer back to the beginning of the file.
// Load file into memory first for faster reads,
// then capture first line from a stringstream instead
getline(fin,buffer,'\x1A'); // Capture entire file into a string buffer
istringstream fullContents(buffer); // Put entire file into a stringstream.
getline(fullContents,firstLine,'\n'); // Capture first line from the stringstream instead of from the file.
cout << firstLine << '\n'; // Prove we got it.
fin.close(); // Close the file
}
return 0;
}
Using the following sample file:
This is the first line.
This is the second line.
This is the last line.
You will get the following output:
This is the first line.
This is the first line.
The prototypes for getline are:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
so, as the error message clearly states, you can't call it with one argument...
Assuming cuvant is an std::string, the correct call is
std::getline(f, cuvant);

C++ length of file and vectors

Hi I have a file with some text in it. Is there some easy way to get the number of lines in the file without traversing through the file?
I also need to put the lines of the file into a vector. I am new to C++ but I think vector is like ArrayList in java so I wanted to use a vector and insert things into it. So how would I do it?
Thanks.
There is no way of finding the number of lines in a file without reading it. To read all lines:
1) create a std::vector of std::string
3 ) open a file for input
3) read a line as a std::string using getline()
4) if the read failed, stop
5) push the line into the vector
6) goto 3
You would need to traverse the file to detect the number of lines (or at least call a library method that traverse the file).
Here is a sample code for parsing text file, assuming that you pass the file name as an argument, by using the getline method:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
int main(int argc, char* argv[])
{
std::vector<std::string> lines;
std::string line;
lines.clear();
// open the desired file for reading
std::ifstream infile (argv[1], std::ios_base::in);
// read each file individually (watch out for Windows new lines)
while (getline(infile, line, '\n'))
{
// add line to vector
lines.push_back (line);
}
// do anything you like with the vector. Output the size for example:
std::cout << "Read " << lines.size() << " lines.\n";
return 0;
}
Update: The code could fail for many reasons (e.g. file not found, concurrent modifications to file, permission issues, etc). I'm leaving that as an exercise to the user.
1) No way to find number of lines without reading the file.
2) Take a look at getline function from the C++ Standard Library. Something like:
string line;
fstream file;
vector <string> vec;
...
while (getline(file, line)) vec.push_back(line);
Traversing the file is fundamentally required to determine the number of lines, regardless of whether you do it or some library routine does it. New lines are just another character, and the file must be scanned one character at a time in its entirety to count them.
Since you have to read the lines into a vector anyways, you might as well combine the two steps:
// Read lines from input stream in into vector out
// Return the number of lines read
int getlines(std::vector<std::string>& out, std::istream& in == std::cin) {
out.clear(); // remove any data in vector
std::string buffer;
while (std::getline(in, buffer))
out.push_back(buffer);
// return number of lines read
return out.size();
}