I'm reading the individual lines from a text file and attempting to print them out on individual lines in the command prompt, but the text just flashes really quickly and disappears.
I is set to the number of lines in readable.txt
cout << "These are the names of your accounts: " << endl;
for (int b = 1; b <= i; b++)
{
fstream file("readable.txt");
GotoLine(file, b);
string line;
file >> line;
cout << line << endl;
}
cin.ignore();
break;
Any help would be greatly appreciated.
error:
Opening a fstream inside a loop? that is suicide, your fstream is always the same why are you opening it for every iteration?
The text probably disappears because your program reaches the end and auto exits you should make him wait before the break or before it reaches the end
You don't need to reopen file every time and invoke GotoLine(file, b); you can open it once outside the for loop and read strings via std::getline(file, line).
If you want to watch the output, insert system("pause") just after the for loop. If you want to pause input after each line, insert getchar() in the end of the for loop (inside of it)
Firstly avoid opening a file inside a for loop. You are doing a lot of mess here.
Try this code
std::ifstream file("readable.txt");
file.open("readable.txt");
if(file.fail())
{
std::cout << "File cannot be opened" << std::endl;
return EXIT_FAILURE;
}
std::string line;
while std::getline(file, line) // This line allows to read a data line by line
{
std::cout << line << std::endl;
}
file.close();
system("PAUSE"); // This line allows the console to wait
return EXIT_SUCCESS;
The break is nonsense (if the snippet is not in a loop or switch.
My guess for the disappearing text is an interference with a IDE. Try it in a terminal/console.
And as in the other answers, file open should be outside the loop.
#include <iostream>
#include <fstream>
using namespace std;
void GotoLine(fstream &f, int b)
{
char buf [999];
while (b > 0) { f.getline (buf, 1000); b--; }
}
int main ()
{
int i = 5;
cout << "These are the names of your accounts: " << endl;
for (int b = 1; b <= i; b++)
{
fstream fl("readable.txt");
GotoLine(fl, b);
string line;
fl >> line;
cout << line << endl;
}
}
Related
I want to load data from .txt file to variable and working with them (like calculate). When I open data, I can read them, but I donĀ“t know to work with data.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
fstream newfile;
string file;
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
while (getline(newfile, file)) {
cout << file << "\n"; //I GET OUTPUT CORRECTLY
}
newfile.close();
}
else
cout << "Error. \n";
cout << file << "\n"; //HERE IS PROBLEM. OUTPUT IS EMPTY
return 0;
}
I tried global variable, but it not solved. What should I do to correct it? Thanks
What you call "PROBLEM" in the comment is not a problem. file never contains more than a single from the file. The last call to getline will not read a line because there is nothing left in the file when you reach its end. So when you call
std::cout << file;
after that loop, it is to be expected that file is empty. If you want to use the lines later you should store them somewhere, eg in a std::vector<std::string>> :
int main()
{
fstream newfile;
std::vector<std::string> data; // vector to hold all lines
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
string line; // better name (file->line)
while (getline(newfile, line)) {
cout << line << "\n";
data.push_back(line); // add the line to data
}
newfile.close();
}
else
cout << "Error. \n";
for (const auto& l : data) std::cout << l << '\n';
return 0;
}
This program is supposed to tell the user how many words and lines are in their program (text file only). The two functions that I have written both work, except the num_of_lines function is counting one more line than is correct every time and the num_of_words function is off by about 300 words every time. Not sure what I am doing wrong here. Any help will be greatly appreciated, thanks. I copy and pasted an output after my code and compared it to wc.
#include <iostream>
#include <fstream>
#include <cctype>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_words(string name)
{
int cnt2 = 0;
ifstream iwords;
iwords.open(name);
string w;
if(iwords.is_open())
{
while(iwords >> w)
{
cnt2++;
}
}
else cerr <<"can not open" + name << endl;
iwords.close();
return(cnt2);
}
int num_of_lines(string name)
{
int cnt3 = 0;
string line;
ifstream ilines;
ilines.open(name);
if(ilines.is_open())
{
while(getline(ilines, line))
{
cnt3++;
}
}
else cerr <<"can not open" + name << endl;
ilines.close();
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(string name);
if(argc == 1)die("usage: mywc your_file");
string file;
file = argv[1];
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int b;
b = num_of_words(file);
cout <<"Words: " << b << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Zacharys-MBP:c++ Zstow$ my sample.txt
Chars: 59526
Words: 1689
Lines: 762
Zacharys-MBP:c++ Zstow$ wc sample.txt
761 2720 59526 sample.txt
Zacharys-MBP:c++ Zstow$
Most files (especially programs) will end in a new line. You may not see this in your editor but it is probably there. You will have to check the last line to see if it actually contains any content, or if it is empty.
The istream operator (>>) will detect any group of characters between whitespace to be a "word." So if you're parsing programs, you may have:
for(int i=1; i<73; i++)
The istream operator will see 4 words: [for(int, i=1;, i<73;, i++)]
I have two files. main.cpp:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("file.txt");
if (!file.good()) {
cout << "Error." << endl;
return 1;
}
int n;
while (!file.eof()) {
file.clear();
file >> n;
if (!file.good() && !file.bad()) {
continue;
} else {
cout << "Hardware error." << endl;
break;
}
cout << n << endl;
}
file.close();
return 0;
}
and file.txt:
a 1 2 321b9 ac.de ef##g 5 #3
I'd like to read only integers from this file and write them out to the console. When file contains only integers program works well but when it contains any invalid characters then I get infinite loop. How can I fix that?
The loop is because the stream doesn't extract the character that is not an integer. You need to extract it before attempting to read another integer.
A small tweak could be all that is needed;
// on a failed read...
file.clear();
char dummy;
file >> dummy;
continue;
A side note on the use of while (!file.eof()); it is generally not recommended to do this. There are several Q&A on SO on this issue.
I am trying to read lines from a .txt file and print them out using std::cout. My code is posted below, but currently is not passing any lines to the vector during the while loop. Where did I go wrong?
int main(int argc, const char * argv[]) {
std::ifstream input("input1.txt");//(argv[1]);
if (!input.good()) {
cerr << "Can not open the grades file "; //<< argv[1] << "\n";
return 1;
}
std::vector<string> art;
string x; // Input variable
// Read the scores, appending each to the end of the vector
cout << "Start While:"; //For Debugging Purposes
while (getline(input, x)) {
art.push_back(x);
}
for (int i=0; i<art.size(); i++) {
cout << art[i] << "\n";
}
return 0;
}
Turns out Xcode was just being difficult. After moving a few files around and running it in the compiler it worked.
I'm quite new to C++ programming, and I'm having trouble reading from an already open file. What I'm doing is writing to a file, reading from it, adding to the end of it, and then trying to read from it again without having to close the original ifstream. The code is as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream myFile ("example.dat");
// Open and write to file
if (myFile.is_open())
{
myFile << "This is a line." << endl;
myFile << "This is another line." << endl;
myFile.close();
}
else cout << "no";
// Open and read from file
string line;
ifstream myFilein ("example.dat");
if (myFilein.is_open())
{
while (getline(myFilein,line))
{
cout << line << myFilein.tellg() << endl;
}
//myFilein.close();
}
// Open and add to end of file
if (!myFile.is_open())
{
myFile.open("example.dat", ios::app);
myFile << "This is the last line." << endl;
myFile.close();
}
//myFilein.open("example.dat", ios::ate);
// Read from already open file
myFilein.seekg(0, ios::beg);
if (myFilein.is_open())
{
cout << "myFilein is open. " << myFilein.tellg() << endl;
while (!myFilein.eof())
{
getline(myFilein, line);
cout << line << endl;
}
}
myFilein.close();
int holdClose;
cin >> holdClose;
return 0;
}
Obviously, something is going wrong, as tellg() is returning a value of -1 after the initial read (i.e., after it hits the end of the file), but I'm not entirely sure why it's returning -1, since I'm trying to reset the position to the beginning of the file. Is there something I'm missing or misunderstanding about how this works? If I close and re-open the file, then it's fine, but I'm curious if there's a way to keep reading from it without having to close it, if that makes sense. Thank you for your help :)
You didn't clear the state of the stream, thus the seekg call did nothing. You need to add myFilein.clear() before the repositioning.