C++ print first ten lines in a file - c++

I have this code but every time I run it,it only prints 11(the number of words in the array) over and over again when the amount of words is over 10. When the amount of words is under 10, nothing prints. Please help
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string word;
fstream file;
int count = 1;
file.open("file.txt");
int numOfLines=0;
while(!file.eof())
{
getline(file,word);
numOfLines++;
}
if(numOfLines<10)
{
while(!file.eof())
{
getline(file,word);
cout << word << endl;
count++;
}
cout << "The entire file has been displayed";
}
else
{
for(int i=0; i<10;i++)
{
cout << word << endl;
}
}
}

To read and print the first ten lines in a file:
#include <iostream>
#include <fstream>
int main()
{
std::string word;
std::fstream file;
file.open("file.txt");
if(!file.is_open())
return -1;
int numOfLines = 0;
while(getline(file, word) && numOfLines < 10){
std::cout << word << std::endl;
numOfLines++;
}
}
Live sample
Note that I removed using namespace std; it' s not a good practice, more in Why is "using namespace std;" considered bad practice?

Related

Is there a way to print individual words from a .txt file without leaving out lines?

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string readFileToString(string fileName) {
fstream file;
string word;
string returnMe;
returnMe.resize(200);
file.open(fileName.c_str());
while (file >> word) {
returnMe += word + " ";
}
file.close();
return returnMe;
}
int main() {
string fileName = "example.txt";
cout << readFileToString(fileName);
}
I have this code but I have several lines in my txt file and it completely ignores them.
If you want to print out all the words in the text file then you can use the following program:
#include <iostream>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream inputFile("input.txt");
std::string word, line;
if(inputFile)
{
while(std::getline(inputFile, line)) //go line by line
{
//std::cout<<line<<std::endl; //this prints the line
std::istringstream ss(line);
while(ss >> word) //go word by word
{
std::cout << word << std::endl;
}
}
}
else
{
std::cout << "File cannot be opened" << std::endl;
}
return 0;
}
The output of the above program can be seen here.

How to put numbers from txt file into vector in c++

I must say I'm completely new to C++. I got the following problem.
I've got a text file which only has one 8 digits number
Text-File: "01485052"
I want to read the file and put all numbers into a vector, e.g. Vector v = ( 0, 1, 4, 8, 5, 0, 5, 2 ). Then write it into another text file.
How do I implement it the best way? That's what I made possible so far:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char matrikelnummer[100];
cout << "Enter file name: ";
cin >> matrikelnummer;
// Declare input file stream variable
ifstream inputFile(matrikelnummer);
string numbers;
//Check if exists and then open the file
if (inputFile.good()) {
//
while (getline(inputFile, numbers))
{
cout << numbers;
}
// Close the file
inputFile.close();
}
else // In case TXT file does not exist
{
cout << "Error! This file does not exist.";
exit(0);
return 0;
}
// Writing solutions into TXT file called Matrikelnummer_solution.txt
ofstream myFile;
myFile.open("Matrikelnummer_solution.txt");
myFile << "Matrikelnummer: " << numbers << '\n';
myFile.close();
return 0;
}
You can use the following program for writing the number into another file and also into a vector:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream inputFile("input.txt");
std::string numberString;
int individualNumber;
std::vector<int> vec;
if(inputFile)
{
std::ofstream outputFile("outputFile.txt");
while(std::getline(inputFile, numberString,'\n'))//go line by line
{
for(int i = 0; i < numberString.size(); ++i)//go character by character
{
individualNumber = numberString.at(i) - '0';
outputFile << individualNumber;//write individualNumber into the output file
vec.push_back(individualNumber);//add individualNumber into the vector
}
}
outputFile.close();
}
else
{
std::cout<<"input file cannot be openede"<<std::endl;
}
inputFile.close();
//print out the vector
for(int elem: vec)
{
std::cout<<elem<<std::endl;
}
return 0;
}
The output of the above program can be seen here.
Read from file to numbers using inputFile >> numbers. Then, add each digit character of the string to a std::vector.
Also, to write to the file, write each element of vector in a for loop.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char matrikelnummer[100];
cout << "Enter file name: \n";
cin >> matrikelnummer;
// Declare input file stream variable
ifstream inputFile(matrikelnummer);
string numbers;
vector<int> individualNumbers;
//Check if exists and then open the file
if (inputFile.good()) {
inputFile >> numbers;
for (int i = 0; i < numbers.length(); i++) {
if (numbers[i] >= '0' && numbers[i] <= '9')
individualNumbers.push_back(numbers[i] - '0');
}
// Close the file
inputFile.close();
}
else // In case TXT file does not exist
{
cout << "Error! This file does not exist.";
exit(0);
return 0;
}
// Writing solutions into TXT file called Matrikelnummer_solution.txt
ofstream myFile;
myFile.open("Matrikelnummer_solution.txt");
myFile << "Matrikelnummer: ";
for (int number : individualNumbers) {
myFile << number << " ";
}
myFile << endl;
myFile.close();
return 0;
}

C++ function `getline()` doesn't work correctly for char[]

I need to extract the first 150 characters from a line and save them in a char[] array (no strings allowed). My code below doesn't work and i just can't find the reason why:
#include <ifstream>
#include <iostream>
using namespace std;
int main()
{
ifstream myFile;
myFile.open("message.txt");
if(!myFile.is_open()) cout<<"error"; //added this after edit
const int SIZE = 151;
char buffer[SIZE]={};
while(myFile.getline(buffer, 151)){
buffer[150]='\0';
cout<<buffer<<endl;
}
myFile.close();
}
Here's a snippet of "message.txt":
abcdefg
hijklmn
opqrstuv
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
hello
It simply prints out nothing. The file "message.txt" exists and has several lines of characters in it. Where am I wrong?
EDIT: if the characters on a line are less than 150, they should all be read. If they are more than 150, the rest should be ignored.
If you are trying to read the first 150 characters of the 1st line, then you don't need the while loop. And you don't need to null-terminate the buffer manually, istream::getline() will do that for you, eg:
#include <ifstream>
#include <iostream>
using namespace std;
int main()
{
ifstream myFile("message.txt");
if (!myFile.is_open())
{
cout << "error";
return 0;
}
const int SIZE = 151;
char buffer[SIZE] = {};
myFile.getline(buffer, SIZE);
cout << buffer << endl;
myFile.close();
return 0;
}
If you want to read the first 150 characters of a specific line only, then you need a loop to skip all lines regardless of their length until you reach the desired line, and then you can read the 150 characters of just that line, eg:
#include <ifstream>
#include <iostream>
#include <limits>
using namespace std;
int main()
{
ifstream myFile("message.txt");
if (!myFile.is_open())
{
cout << "error";
return 0;
}
size_t lineIndex = ...;
while (lineIndex > 0)
{
if (!myFile.ignore(numeric_limits<streamsize>::max(), '\n'))
{
cout << "error";
return 0;
}
if (myFile.eof())
{
cout << "eof";
return 0;
}
--lineIndex;
}
const int SIZE = 151;
char buffer[SIZE] = {};
myFile.getline(buffer, SIZE);
cout << buffer << endl;
myFile.close();
return 0;
}
If you want to read the first 150 characters of each line, then after a successful read you need to skip any remaining characters prior to a line break before you can then read the next line, eg:
#include <ifstream>
#include <iostream>
#include <limits>
using namespace std;
int main()
{
ifstream myFile("message.txt");
if (!myFile.is_open())
{
cout << "error";
return 0;
}
const int SIZE = 151;
char buffer[SIZE] = {};
do
{
myFile.getline(buffer, SIZE);
if (myFile.bad())
{
cout << "error";
return 0;
}
if (myFile.fail())
{
// SIZE-1 characters were extracted before a line break
// was reached, need to reset the error to keep going...
myFile.clear();
myFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << buffer << endl;
}
while (!myFile.eof());
myFile.close();
return 0;
}

How do I remove all the punctuation from the file that I am reading from?

This is my main method in a file called main.cpp:
#include <iostream>
#include "ReadWords.h"
#include "Writer.h"
#include <cctype>
#include <string>
using namespace std;
int main() {
int count;
int length;
string word;
cout << "Please enter a filename: " << flush;
char filename[30];
cin >> filename;
This is where I am trying to delete all the punctuation in the file. Currently I am able to read the file and print all the values. I am struggling to access the file and delete the punctuation. I know that I am to use ispunct. I have tried many different implementations but cannot get it to work. How do I delete all the punctuation in the file?
ReadWords reader(filename);
while (reader.isNextWord()){
count = count + 1;
reader.getNextWord();
}
cout << "There are: " << count << " words in this text file" << endl;
return 0;
}
This is another file called ReadWords where I have all my method declarations: I don't think this is relevant/needed
#include "ReadWords.h"
#include <cstring>
#include <iostream>
using namespace std;
void ReadWords::close(){
}
ReadWords::ReadWords(const char *filename) {
//storing user input to use as the filename
//string filename;
wordfile.open(filename);
if (!wordfile) {
cout << "could not open " << filename << endl;
exit(1);
}
}
string ReadWords::getNextWord() {
string n;
if(isNextWord()){
wordfile >> n;
return n;
}
}
bool ReadWords::isNextWord() {
if (wordfile.eof()) {
return false;
}
return true;
}
Read from the input file one character at a time.
For each character you read:
If the character is not punctuation, write it to the output file.
If the character is punctuation, don't write it to the output file.

How to open any input file whether it contains words or numbers and prints it out. C++

So Lets say this is what the input file contains
12
Hello
45
54
100
Cheese
23
How would I print it out on the screen in that order.
This is what I had but it skips some lines.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
string word;
int loop = 0;
ifstream infile;
infile.open("arraynumbers.txt");
while(infile >> number >> word)
{
if( infile >> number)
{
cout << number << endl;
}
if(infile >> word)
{
cout << word << endl;
}
}
return 0;
}
I suggest using www.cplusplus.com to answer these questions.
However, you are on the right track. Since you are just outputting the contents of the file to stdout, I suggest using readline() and a string. If you need to access the numeric strings as ints, use the atoi() function.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream file("arraynumber.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else cout << "Error opening arraynumber.txt: File not found in current directory\n";
return 0;