Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have been asked to develop program to count no. of lines and words in the file, this is my trial, my teacher said that I cant use >> operator for counting words and comparing but I could not handle it.
#include <iostream>
#include <fstream>
using namespace std;
int numberLines = 0;
int numberWords = 0;
void numberOfLines(){
cout<<"number of lines is " << numberLines << endl;
}
void numberWords(){
cout << "number of words is " << numberWords <<endl;
}
int main(){
string line;
char a = '';
ifstream myfile("files.txt");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
cout<< line << endl;
numberLines++;
}
if ( a == ' '){
NumberWords++;
}
}
myfile.close();
}
numberOfLines();
numberOfWords ();
}
What you can do is add a 3rd argument to getline(). This lets it pull data from the stream until it hits a character. Doing getline(cin, line, ' ')takes all the data until the next and puts it into line. Your code might look like:
while(getline(inFile, line))
{
++numlines;
stringstream lineStream(line);
while(getline(lineStream, line, ' '))
{
++numWords;
}
}
The outer loop goes through the file and stores each line into line, then the inner goes through that line and counts each space. which correlates to a word.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i want to convert a sentence like 'good boy' to ascii code . i know the code that is a loop and print the ascii code of each character of sentence but i don't want this. i want that the ascii code of sentence (all characters alltogether) in long for example 1259788712..
You can use string to handle it.
#include <iostream>
#include <sstream> // use stringstream
using namespace std;
// turn int into string
string IntTOstring(int);
int main(void)
{
string sIn,sOut;
// input
sIn = "good boy";
sOut="";
for (int i=0 ; i<sIn.length() ; i++ ) {
// get one char from sIn each time
int temp=sIn.c_str()[i];
// turn int into string & save in sOut
sOut += IntTOstring(temp);
}
cout << sOut << endl;
return 0;
}
// use stringstream to convert int to string
string IntTOstring(int i){
stringstream ss;
ss << i;
return ss.str();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
As the title suggests I am trying to find a specific word inside a file, and then deleting the line including it, but what I do here destroys the content of the file:
cin>>ID; //id of the line we want to delete
ifstream read;
read.open("infos.txt");
ofstream write;
write.open("infos.txt");
while (read >> name >> surname >> id) {
if (ID != id) {
write << name << " " << surname << " " << id << endl;
}
else write << " ";
}
read.close();
write.close();
Both of your files have same name. Calling basic_ofstream::open destroys content of a file if it already exists. In your case you destroyed data in input file before doing anything. Use different name and later rename. I assume line in input is ended with "\n" so we can use getline(). Then we need to tell if word is present in line and for that there is this function. std::string:npos is returned if line doesn't contain word.
#include <cstdio> // include for std::rename
#include <fstream>
#include <string>
void removeID() {
std::string ID;
cin >> ID; //id of the line we want to delete
ifstream read("infos.txt");
ofstream write("tmp.txt");
if (read.is_open()) {
std::string line;
while (getline(read, line)) {
if (line.find(ID) != std::string::npos)
write << line;
}
} else {
std::cerr << "Error: coudn't open file\n";
/* additional handle */
}
read.close();
write.close();
std::remove("infos.txt");
std::rename("tmp.txt", "infos.txt");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to read from file line by line and print it on the screen:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream out("note.txt");
for (int i = 0; i < 10; i++)
out << i << " " << (i<<1) << "\n";
out.close();
ifstream fin;
fin.open("note.txt");
string line;
for (int i = 0; i < 10; ++i)
{
getline(fin, line);
cout << line << "\n";
}
return 0;
}
Is this approach correct? Cant I do it without a string variable (without string line in code)?
Instead of using a for loop you can use a while loop:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
string line;
ifstream out("note.txt");
while(getline(out, line)) {
cout << line << endl;
}
out.close();
}
If you are forced not to use strings then you can try a char buffer char buf[1024]. It must be pointed out that this approach is dangerous and error prone. If a line has more than 1024 characters then a buffer overflow will occur. Buffer overflow is the cause of many vulnerabilities and crashes. That being said, if you really have to use this method I would suggest you to be very careful by making the appropriate checks.
Copying a file verbatim is a simple as streaming out its stream buffer:
ifstream fin;
fin.open("note.txt");
std::cout << fin.rdbuf();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I will first off say that yes, this is a homework assignment, but my teacher is really not too clear on how to do things.
I'm asked to, in c++, Write a function that will pass words from a file one at a time. The function will calculate the word length and then print out TO SCREEN the word and its length on its own line.
The main will open your input file, read it word by word in a loop and then pass the word into your function for it to be printed.
I know how to open a file using fstream and all that, read it word by word, but not in a loop or a function by the void readfile () one. My problem here is putting everything together.
This is my program to open a file, get the length and display it in a parallel array
//declare parallel arrays
string words [MAXSIZE];
//open files
outputFile.open("output.txt");
inputFile.open ("/Users/cathiedeane/Documents/CIS 22A/Lab 4/Lab 4 Part 2/lab4.txt");
//inputvalidation
while (!inputFile.eof())
{
for(int i = 0; i < MAXSIZE; ++i)
{
outputFile << words[i] << " " << endl;
inputFile >> words[i];
}
inputFile.close();
}
for (int i= 0; i <= MAXSIZE; i++)
{ cout << words[i] << ":" << words[i].size()<< endl;
outputFile << endl;
}
//close outputfile
outputFile.close();
return 0;
}
So basically your assignment is :
function read_word
/* what you have to work on */
end
function read_file_word_by_word
open file
while not end_of_file
word = read_word
print word, word_length
end
close file
end
To read a word, you need to define what it is. Usually it's a bunch of letters, delimited by other characters that are not letters (whitespace, commas, etc.).
You could read the file character by character and store them when they are letters until you encounter some other kind of character. What you have stored is a word, and you can get its length quite easily.
Tip: http://www.cplusplus.com/reference/istream/istream/get/ allows you to read a single character from a file.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void func(const string& word)
{
//set field width
cout.width(30);
cout << left << word << " " << word.size() << endl;
}
int main(int argc, char* argv[])
{
ifstream ifs("F:\\tmp\\test.txt");
if(ifs.fail())
{
cout << "fail to open file" << endl;
return -1;
}
_Ctypevec ct = _Getctype();
for(char ch = 0; ch < SCHAR_MAX; ch++)
{
//set all punctuations as field separator of extraction
if(ispunct(ch))
{
(const_cast<short*>(ct._Table))[ch] = ctype<char>::space;
}
}
//change the default locale object of ifstream
ifs.imbue(locale(ifs.getloc(), new ctype<char>(ct._Table)));
string word;
while(ifs >> word)
{
func(word);
}
ifs.close();
}
You'll obviously want to separate each word in to its own string index to store them in your array. To separate each word, establish a break point like char break = ' '; Then, while your IOStream is reading the file, just add the words to the index using an iterator (i++)
Now that some time has passed since you asked the question, I would like to add that this could be answered in a quite small amount of code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void printString( const string & str ) { // ignore the & for now, you'll get to it later.
cout << str << " : " << str.size() << endl;
}
int main() {
ifstream fin("your-file-name.txt");
if (!fin) {
cout << "Could not open file" << endl;
return 1;
}
string word; // You only need one word at a time.
while( fin >> word ) {
printString(word);
}
fin.close();
}
A small note on fin >> word, this expression returns true for as long as there was a word read into the string. It will also skip any whitespace (tab, space and newline) by default.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Say I have a text file containing 10 lines. I want to move to line #5, clear everything below it, and append some new texts after that. What is the most compact way to achieve this using C++ of stream (just in case I missed some ofstream features)?
Read N lines while writing to a second file, then write all the new text to the new file after that.
Use IOstream to open the file and store the first five lines in an array and recreate the test file using the array and whatever other lines you want. Here is a code example:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
const int linesToRead = 5; //How many lines to read before stopping
string lines [linesToRead];
int line = 0;
ifstream myinputfile ("example.txt");
if (myinputfile.is_open())
{
while ( myinputfile.good() && line<=linesToRead )
{
if(line<linesToRead)
{ //Stop reading at line 5
getline (myinputfile,lines[line]);
cout << lines[line];
}
line++;
}
myinputfile.close();
}
else cout << "Unable to open file";
//Begin creating new file
const int numberOfNewLines = 7;
string newlines[numberOfNewLines] = {"These", "are", "some", "of", "the", "new", "lines"}; //lines to be added after the previous 5
ofstream myoutputfile ("example.txt");
if (myoutputfile.is_open())
{
for(int i = 0; i<linesToRead; i++){
myoutputfile << lines[i] << "\n";
}
for(int i = 0; i<numberOfNewLines; i++){
myoutputfile << newlines[i] << "\n";
}
myoutputfile.close();
}
else cout << "Unable to open file";
return 0;
}