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;
}
Related
okay I've searched everywhere and couldn't get my hand on it so ..
i'm doing a library system where a librarian enters his username and the program checks if he is one of the librarians or not
i'm stuck on the comparing part , i tried using getline but it gave me an error , tried gets_s and used a char array instead of a string and still didn't work
kindly help me with what i should do
using namespace std;
#include <iostream>
#include <string>
#include <fstream>
int main()
{
//opening files
ifstream readUsername;
ofstream enterUsername;
//variables
string existUsername;
string enteredUsername;
//reading files
readUsername.open("librarian usernames.txt");
if (readUsername.fail())
{
cout << "can't open file" << endl;
}
enterUsername.open("entered librarian username.txt");
if (enterUsername.fail())
{
cout << "can't open file" << endl;
}
while(!readUsername.eof)
{
readUsername >> existUsername;
}
enterUsername << enteredUsername;
readUsername.close();
enterUsername.close();
enterUsername.clear();
system("pause");
return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
infile.open("listOfWords.txt"); //open file
for(string listOfWords; getline(infile, listOfWords, '.'); ) //read sentences including
//spaces
cout<<listOfWords; //this displays
return 0;
}
This shows you how to output the text so you should just save both files to a variable then compare the variables.
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 am trying to count the number of lines in a text file but each time i'm running this code i am getting 1987121509 as the number of lines. Can you please tell me how i can modify my code to get the correct number of lines? Thank you.
Here's the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine;
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
cout<<"Error opening file.";
}
else
{
cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
++numLine; //increment numLine each time a line is found
}
cout<<"\nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}
Here's the correct code(I found out after asking the question)
Silly mistake of not initializing the variable correctly.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine = 0; //didn't set it to zero.
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
cout<<"Error opening file.";
}
else
{
cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
++numLine;
}
cout<<"\nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}
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.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile("hey.txt");
myfile >> line;
cout << line;
system("pause");
return 0;
}
Why does this not print out what is in my "hey.txt" file?
This should do the job, If you are new to these things please read http://www.cplusplus.com/doc/tutorial/files/
EDIT: in article above .good() is a bad practice, look here if you need to more detail Testing stream.good() or !stream.eof() reads last line twice
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while(getline(myfile, line)) {
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}