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

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);

Related

getline(stream, string) from example is rejected by editor(VS2019)

The example is taken from:
[http://www-h.eng.cam.ac.uk/help/tpl/languages/C++/1AComputing/Mich/index.php?reply=extraReadingfromfiles#extraReadingfromfilesanchor][1]
I wrote the code without the while loop to read file, the example used getline(stream, strgvar), but this is not admited by the editor
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string message;
ifstream fin; // variable to store information about a file
fin.open("s.txt"); // trying to open file for reading
// next line would try to check if file has been opened succesfully
if (not fin.good())
{
cout << "\n\t Couldn't open the s file." << endl;
cout << "\n\t It needs to be in the same folder as your program."
<<endl;
return 1; // In the main function this line quits from the
whole program.
}
// we have menaged to open the file. Now we'll read a line from the file into the string
while (message!="works!")
{
fin >> message;
cout << message << " ";
}
//getline(fin,message);
}
My questions is why the line now commented is rejected ?
fin>>message;
The stream extraction operator '>>' is used when you want to read a single word from file.
Find complete explanation at : https://www.google.com/amp/s/www.geeksforgeeks.org/cpp-program-read-file-word-word/amp/
While
getline(fin,message);
In this, a full line from the file will be read in message variable. It will continue reading and assigning file contents till a '\n' (Line Deliminator) character does not appear. And thats why you getline() statement is rejected.
For complete explanation visit : http://www.cplusplus.com/forum/windows/48212/
Your program is expected to read a word at a time. And to accomplish this, fin>>mesage is used. Basically stream extraction operator read the contents till a space appears, and hence it is used to read single word.
And if you still want to use getline (), then add a third parameter to your function call as space character ' '.
Like
getline(fin,message,' '); // and done
Basically the third parameter of getline function is Deliminator, by default it is '\n', but if you want to define your own Deliminator, you can do so by providing third parameter. It will read the contents of file till the Deliminator does not occurs while reading.
To use std::getline() include <string> in the header.
https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/2whx1zkx(v=vs.100)
istream also has a getline. More details here
https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa277361(v=vs.60)

How to read lines from a file using the ifstream?

I have a text file with the following information in it:
2B,410,AER,2965,KZN,2990,,0,CR2
2B,410,ASF,2966,KZN,2990,,0,CR2
2B,410,ASF,2966,MRV,2962,,0,CR2
2B,410,CEK,2968,KZN,2990,,0,CR2
2B,410,CEK,2968,OVB,4078,,0,CR2
2B,410,DME,4029,KZN,2990,,0,CR2
2B,410,DME,4029,NBC,6969,,0,CR2
2B,410,DME,4029,TGK,\N,,0,CR2
(it is airline route info)
I'm trying to loop through the file and extract each line into a char* - simple right?
Well, yes, it's simple but not when you've completely forgotten how to write successful i/o operations! :)
My code goes a little like:
char * FSXController::readLine(int offset, FileLookupFlag flag)
{
// Storage Buffer
char buffer[50];
std::streampos sPos(offset);
try
{
// Init stream
if (!m_ifs.is_open())
m_ifs.open(".\\Assets\\routes.txt", std::fstream::in);
}
catch (int errorCode)
{
showException(errorCode);
return nullptr;
}
// Set stream to read input line
m_ifs.getline(buffer, 50);
// Close stream if no multiple selection required
if (flag == FileLookupFlag::single)
m_ifs.close();
return buffer;
}
Where m_ifs is my ifStream object.
The problem is that when I breakpoint my code after the getline() operation, I notice that 'buffer' has not changed?
I know it is something simple, but please could someone shed some light onto this - I'm tearing my forgetful hair out! :)
P.S: I never finished writing the exception handling so it is pretty useless right now!
Thanks
Here is a fix with some important c++ libraries you may want to learn, and what I believe a better solution. Since you just need your final result to be strings:
// A program to read a file to a vector of strings
// - Each line is a string element of a vector container
#include <fstream>
#include <string>
#include <vector>
// ..
std::vector<std::string> ReadTheWholeFile()
{
std::vector<std::string> MyVector;
std::string JustPlaceHolderString;
std::ifstream InFile;
InFile.open("YourText.txt"); // or the full path of a text file
if (InFile.is_open())
while (std::getline(InFile, PlaceHolderStr));
MyVector.push_back(PlaceHolderStr);
InFile.close(); // we usually finish what we start - but not needed
return MyVector;
}
int main()
{
// result
std::vector<std::string> MyResult = ReadTheWholeFile();
return 0;
}
There are two basic problems with your code:
You are returning a local variable. The statement return buffer; results in a dangling pointer.
You are using a char buffer. C-style strings are discouraged in c++, you should always prefer std::string instead.
A far better approach is this:
string FSXController::readLine(int offset, FileLookupFlag flag) {
string line;
//your code here
getline(m_ifs, line) //or while(getline(my_ifs, line)){ //code here } to read multiple lines
//rest of your code
return line;
}
More information about std::string can be found here

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
}
}

C++ Read from text file

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

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();
}