I think i have a beginners question.
I try to read a file line by line.
The file is in /home/myhomedir and called text.txt .
The content of the file is
1
2
3
4
The file has access right for everyone to read and write.
I wanted: open the file and read it one line after another.
So I tried:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
try
{
ifstream myfile ;
myfile.open("/home/myhomedir/text.txt", ios::in);
if(myfile.is_open())
{
string line;
while (getline(myfile, line)) {
// do nothing, just get a line
// *
}
}
}
catch(int ex)
{
}
return 0;
}
The place marked with * is reached (used the debug feature of netbeans). however line is empty and loop seemed to be entered only once.
Like if an empty file is opened.
What am I doing wrong?
The reason is, you don't know how to use debugger. I've modified your code:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
try
{
ifstream myfile ;
myfile.open("/home/enedil/text.txt", ios::in);
if(myfile.is_open())
{
string line;
while (getline(myfile, line)) {
cout << line; // there's my modification
}
}
}
catch(int ex)
{
}
return 0;
}
The output is
1234
So everything's correct.
If the content of the file is literally
1 2 3 4
then it has only one line and it is to be expected that "getline" returns false the second time it's called.
Related
I don't understand why my ifstream can not be read in my class. In the main.cpp reading from the stream works fine, but when I pass the ifstream by reference to the c'tor I am not able to read from it. The program compiles fine but the 'inputfile' seems to be empty. In the console, I just see the content of my .txt once which comes from the main.cpp.
Am I doing something wrong with passing the ifstream?
main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "RAM.h"
int main(int argc, char** argv)
{
std::ifstream input;
input.open("\\path\\orders.txt");
std::string line;
while (std::getline(input, line))
{
std::cout << line << std::endl;
}
RAM machine(input);
}
RAM.h:
#pragma once
#include <fstream>
class RAM
{
private:
std::ifstream& inputfile;
public:
RAM(std::ifstream&);
~RAM();
};
RAM.cpp:
#include "RAM.h"
#include <iostream>
#include <fstream>
#include <string>
RAM::RAM(std::ifstream &in) : inputfile(in){
std::string line;
while (std::getline(inputfile, line))
{
std::cout << line << std::endl;
}
}
RAM::~RAM() {
}
orders.txt:
ADD 5
SUB 7
HLT 99
The input file appears to be empty since you have already read all the data in main(). In other words, you're at the end of the file:
// File just opened, at position 0.
std::string line;
while (std::getline(input, line))
{
std::cout << line << std::endl;
}
// File fully read, at end of file.
RAM machine(input);
If you want to re-read it, you'll need to seek back to the start before attempting to re-read in the constructor, something like:
inputfile.seekg(0);
i want to read a full line of strings from a file in order to do some operations. With the bellow code the "Ciphertext" is empty.
my code :
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream myfile("C:\\encr_affine.txt");
string Ciphertext;
while (!myfile.eof())
{
getline(myfile, Ciphertext);
}
//some code here
myfile.close();
}
The answer for reading a line of strings in a file was :
while (getline(myfile, Ciphertext))
{
//reading the ciphertext from the file
}
This is my code.
I am supposed to count the number of 'duck' in a txt file and print string like "There were 2 ducks in animals01.txt"
Now I get no error and nothing return.
Please tell me what's wrong?
#include <iostream> // for printf()
#include <cstdlib> // for exit(), perror()
#include <fstream> // for ifstream
using namespace std;
int main(int argc, char *argv[])
{
if (argc!=2) {
// if argc is not 2, print an error message and exit
cerr << "Usage: "<< argv[0] << " inputFile" << endl;
exit(1); // defined in cstdlib
}
return 0;
int num = 0;
ifstream ifs;
ifs.open(argv[1]);
string line;
do{
getline(ifs, line);
cout<<line<<endl;
if(line == "duck"){num++;}
}while(!ifs.eof());
cout<<"There were"<<num<<"ducks in"<<argv[1]<< endl;
}
You have the line return 0; before you actually did anything, and when you return main() the program is terminated.
By the way, don't use while(!ifs.eof()) because the eof flag only gets set at the first attempt to read past the end of the file, not when you read exactly to the end of the file due to a line break at the end. Do something like this. Also, fix your indenting as it is very misleading.
Read the file word by word.
Example:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string str, strToSearch = "ducks";
int wordCount = 0;
ifstream fin("thisfile.txt");
while (fin >> str) // Will read up to eof() and stop at every whitespace it hits. (like spaces!)
{
if(str==strToSearch)
wordCount++;
}
fin.close();
cout<<"There were"<<wordCount<<"ducks in thisfile.txt"<<endl;
return 0;
}
I've been trying to make a console application in Visual Studio 2015 which will read a text file to a string and then output the string, but I'm having some problems.
The first thing I tried was following the cplusplus.com tutorial:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream myfile("test.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The program didn't open the file.
Despite multiple internet searches and trying over 20 different methods, I still haven't been able to get my program to work. The best result I was able to achieve was a row of meaningless 0s.
Where am I going wrong?
What you are doing wrong is not emitting a useful error message. Rather than printing "Unable to open file", let the computer tell you why it couldn't open the file. For example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
int rv = 0;
string line;
const char * path = argc > 1 ? argv[1] : "test.txt";
ifstream myfile(path);
if( myfile.is_open() ){
myfile.close();
} else {
perror(path);
rv = 1;
}
return rv;
}
I was wanting to know if there was a simple way to set a std::string equal to the contents of a file in C++. So far, I was thinking something like this: (although I haven't tested it, so I don't know if it will work)
#include <fstream>
#include <string>
int main(int argc, char *argv[]){
fstream in("file.txt");
string str;
str = in;
return 0;
}
Is this a way to accomplish this? If not, is there a simple way to do so? Thanks!
Here is one possible solution using vector<string>, each element is a line.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// vector that will store all the file lines
vector<string> textLines;
// string holding one line
string line;
// attach input stream to file
ifstream inputFile("data.txt");
// test stream status
if(!inputFile)
{
std::cerr << "Can't open input file!\n";
}
// read the text line by line
while(getline(inputFile, line))
{
// store each line as vector element
textLines.push_back(line);
}
// optional (stream object destroyed at end of function scope)
inputFile.close();
return 0;
}
There is a standard way:
std::ifstream file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string content( buffer.str() );
References
http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt specially item (8)
try this one
#include <fstream>
#include <cstdlib>
std::string readText(const char* fileName)
{
std::ifstream file(fileName);
if (!file.good())
{
std::cout << "file fail to load..." << fileName;
exit(1);
}
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}