Reading lines from file in C++ - c++

Why can't I get each line in a file printed with this? It outputs nothing.
string line;
ifstream s {"book_list.txt"};
while (getline(s, line)) {
cout << line << endl;
}
I've included fstream, sstream, string, stdio.h, stdlib.h and am using namespace std;

#include<iostream>
#include<fstream>
#include<string>
using namespace std
int main()
{
string line;
ifstream s ("book_list.txt");
if (s.is_open())
{
while ( getline (s,line) )
{
cout << line << endl;
}
s.close(); // Don't forget to close the file
}
else
cout << "Unable to open file";
return 0;
}
I hop it helps.

I guess the file doesnt exist.
Please check with:
if(!s.good()) {
// error
}
or
while (s.good()) {
// process.
}

You should do something like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string sLine = "";
ifstream infile;
infile.open("temp.txt");
if(infile.is_open()){
while (getline(infile, sLine))
{
cout << sLine << endl;
}
}
infile.close();
cout << "Read file completed!!" << endl;
}

#include <iostream>
#include <fsstream>
using namespace std;
int main()
{
string data;
int counter = 0;
ifstream infile("test_file.txt");
while (!infile.eof()){
getline(infile , data);
counter += 1;
}
cout << "The number of lines is : " << counter << endl;
return 0;
}

Related

How to write the result of a function to a file C++

I think this is a pretty simple question, but I didn't find the answer.
I wish to write the result of a function to a file.
The file is open, and I'm able to write a simple string to it, but not the result of the function.
What I am missing?
#include <iostream>
#include <fstream>
using namespace std;
void addingtext(){
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
}
}
int main () {
ofstream file;
file.open("example.txt");
if(file.is_open()){
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext();
//file << addingtext;
file.close();
return 0;
}
addingtext() returns nothing, and writes to std::cout.
You have two options:
Option 1: Make addingtext() return a string, and then write that to the file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::string addingtext() {
std::string result;
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
result += i;
result += "\n";
}
return result;
}
int main() {
ofstream file;
file.open("example.txt");
if (file.is_open()) {
std::cout << "File Open Access \n";
}
file << "Write this to the file";
file << addingtext();
file.close();
return 0;
}
Option 2: Make addingtext() write to the file:
#include <iostream>
#include <fstream>
using namespace std;
void addingtext(ofstream& o) {
for (int i = 0; i < 8; ++i)
{
std::cout << i << endl;
o << i << endl;
}
}
int main() {
ofstream file;
file.open("example.txt");
if (file.is_open()) {
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext(file);
file.close();
return 0;
}
Your function does not return any value.
If it returned a value, such as a string you have created during the running of the addingtext function you could then add that string straight to the file as you are doing there.
I think you want to pass the file stream to your function so it writes to the file instead of std out.
void addingtext(ofstream& stream){
for (int i = 0; i < 8; ++i)
{
stream << i << endl;
}
}
int main () {
ofstream file;
file.open("example.txt");
if(file.is_open()){
std::cout << "File Open Access \n";
}
file << "Write this to the file";
addingtext(file);
//file << addingtext;
file.close();
return 0;
}
If you want your function to return a string, don't declare it's return type as void. I would:
#include <string>
string addingtext(){
string temp;
for (int i = 0; i < 8; ++i)
{
temp += i;
}
return temp;
}

ifstream ofstream on mac

I'm trying to read in a random file (on mac-xcode) and determine the instances of the letter k in the document. Then print the number as an outout file. My problem is that the outfile isn't being written and the nums_k is coming back as 0. I'm not sure if the ifstream is working incorrectly or the ofstream need a different filename established. Here's my source code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("Users/bryanmichaelnorris/documents/extra credit assignment.docx");
string line;
int numks = 0;
while (getline(infile,line)) {
int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k') {
numks++;
}
x++;
}
}
infile.close();
ofstream outfile("number of k's.docx");
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}
Added validations for the opened files.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const char * csInputFileNane="Users/bryanmichaelnorris/documents/extra credit assignment.docx";
ifstream infile(csInputFileNane);
if (!infile.is_open()) {
cerr << "Cannot open file \""<<csInputFileNane<<'"'<<endl;
return -1;
}
string line;
int numks = 0;
while (getline(infile,line))
{ int x = 0;
for (std::string::iterator it=line.begin(); it!=line.end(); ++it) {
if (line[x] == 'k')
{
numks++;
}
x++;
}
}
infile.close();
const char *csOutFileName="number of k's.docx";
ofstream outfile(csOutFileName);
if (!outfile.is_open()) {
cerr << "Cannot open file \""<<csOutFileName<<'"'<<endl;
return -1;
}
outfile << "There are " << numks << " K's in the file." << endl;
outfile.close();
return 0;
}

C++ Write sorted contents of vector<string> to file

This currently reads a .txt file and sorts the contents. I'm trying to get it to write those sorted contents of the vector to a file. Currently it only writes one line, how can I can get it to put all lines in the new file? Thank you so much. -Kaiya
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <fstream>
using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}
int main()
{
string line;
ifstream myfile("weblog.txt");
vector<string> fileLines;
//stack overflow example
if (!myfile) //test the file
{
cout << "Unable to open the file" << endl;
return 0;
}
while (getline(myfile, line))
{
fileLines.push_back(line);
//cout << line << '\n';
}
sort(fileLines.begin(), fileLines.end()); //sorting string vector
for (string &s : fileLines)
{
cout << s << " ";
ofstream newfile ("newfile.txt");
newfile << s << " ";
};
return 0;
}
ofstream newfile ("newfile.txt");
for (string &s : fileLines)
{
cout << s << " ";
newfile << s << " ";
};
Creating newfile for every loop iteration overwrites the content of the file, by default.
Either open newfile before the last loop, or open it in append mode within the loop.
It's because you are creating a new file in each iteration of your loop!
ofstream newfile("newfile.txt");
should be written before the loop.
ofstream newfile ("newfile.txt");
for (string &s : fileLines)
{
cout << s << " ";
newfile << s << " ";
};
ofstream newfile ("newfile.txt");
copy(fileLines.begin(), fileLines.end(), ostream_iterator<string>(newfile, " ") );
Here is my complete code that worked, thanks Xiaotian Pei for your help.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <fstream>
using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}
int main()
{
string line;
ifstream myfile("weblog.txt");
vector<string> fileLines;
if (!myfile) //test the file
{
cout << "Unable to open the file" << endl;
return 0;
}
while (getline(myfile, line))
{
fileLines.push_back(line);
}
sort(fileLines.begin(), fileLines.end()); //sorting string vector
ofstream newfile ("newfile.txt"); //write to new file
for (string &s : fileLines)
{
cout << s << " ";
newfile << s << " ";
}
return 0;
}

Reading "tokens" from a string line in C++ I/O

I am wondering how I can do the following in C++ since I am only familiar with Java.
I have a string which we will call line.
string line = "hello how are you";
In C++ I have retrieved that line from getLine(). I want to traverse through this line so I can count the number of words in this line. The result should be 4, in my example.
In Java, I would have imported Scanner. Then do something like this:
//Other scanner called fileName over the file
while(fileName.hasNextLine()) {
line = fileName.nextLine();
Scanner sc = new Scanner(line);
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
}
I am only using #include<iostream>, fstream and string.
You can use stringstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin,line);
stringstream ss(line);
string word;
int count=0;
while(ss>>word){//ss is used more like cin
count++;
}
cout<<count<<endl;
return 0;
}
http://ideone.com/Yl25KT
I would avoid ifstream::getline and just use ifstream::get instead. You don't even need to use string.
#include <iostream>
int main()
{
int numwords = 1; //starts at 1 because there will be (numspaces - 1) words.
char character;
std::ifstream file("readfrom.txt");
if (file.fail())
{
std::cout << "Failed to open file!" << std::endl;
std::cin.get();
return 0;
}
while (!file.eof())
{
file >> character;
if (character == ' ')
{
numwords++;
std::cout << std::endl;
}
else if (character == '\n') //endline code
{
std::cout << "End of line" << std::endl;
break;
}
else
std::cout << character;
}
std::cout << "Line contained " << numwords << " words." << std::endl;
std::cin.get(); //pause
return 0;
}

Checking if word exists in a text file c++

I need to check if a word exists in a dictionary text file, I think I could use strcmp, but I don't actually know how to get a line of text from the document. Here's my current code I'm stuck on.
#include "includes.h"
#include <string>
#include <fstream>
using namespace std;
bool CheckWord(char* str)
{
ifstream file("dictionary.txt");
while (getline(file,s)) {
if (false /* missing code */) {
return true;
}
}
return false;
}
std::string::find does the job.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool CheckWord(char* filename, char* search)
{
int offset;
string line;
ifstream Myfile;
Myfile.open (filename);
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile,line);
if ((offset = line.find(search, 0)) != string::npos)
{
cout << "found '" << search << "' in '" << line << "'" << endl;
Myfile.close();
return true;
}
else
{
cout << "Not found" << endl;
}
}
Myfile.close();
}
else
cout << "Unable to open this file." << endl;
return false;
}
int main ()
{
CheckWord("dictionary.txt", "need");
return 0;
}
char aWord[50];
while (file.good()) {
file>>aWord;
if (file.good() && strcmp(aWord, wordToFind) == 0) {
//found word
}
}
You need to read words with the input operator.