I'm a bit new to C++ so I'm trying to keep things simple.
I'm trying to apply a loop that simply prints out each number from a txt file. And there are A LOT of numbers.
I've been trying to do this with a for loop but with no success. Here's just one of my attempts:
int main() {
fstream myFile;
myFile.open("resources/numbers.txt");
if (myFile) {
cout << "This file is opened\n";
}
else
return EXIT_FAILURE;
for (i = 1; i<n; i++){
myFile >> n;
cout << n;
}
return 0;
}
I'd prefer not to use arrays or getLine. I just want to take every number from the txt file and print it to the user until every number is printed.
Is there an easy way to do this?
Thanks a million!
Here is how I’d print the number in the file:
std::copy(std::istream_iterator<int>(myFile),
std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, “\n”));
In you example you didn’t declare n so it isn’t clear what the proper type is. The code assumes int and that <algorithm> and <iterator> are included.
#include <cstdlib> // EXIT_FAILURE
#include <iostream>
#include <fstream>
int main()
{
std::ifstream myFile{ "resources/numbers.txt" }; // use c-tor to open
// ^ ifstream ... we only want to read
if (!myFile.is_open()) {
std::cerr << "File couldn't be opened for reading :(\n\n";
return EXIT_FAILURE;
}
std::cout << "File is open for reading.\n\n";
int number;
while(myFile >> number) // as long as integers can be extracted from the stream,
std::cout << number << '\n'; // print them.
} // no need to return anything as main() returns 0 when not return statement
// is present.
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;
}
I have this specific code to read integers from a text file:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
bool contains_number(const string &c);
int main()
{
int from[50], to[50];
int count = 0;
{
string line1[50];
ifstream myfile("test.txt");
int a = 0;
if (!myfile)
{
cout << "Error opening output file" << endl;
}
while (!myfile.eof())
{
getline(myfile, line1[a]);
if (contains_number(line1[a]))
{
count += 1;
myfile >> from[a];
myfile >> to[a];
//cout << "from:" << from[a] << "\n";
//cout << "to:" << to[a] << "\n";
}
}
}
return 0;
}
bool contains_number(const string &c)
{
return (c.find_first_of("1:50") != string::npos);
}
I need to stock these values of from[] and to[] in 2 arrays to use them n another function, I tried to create 2 arrays in a simple way and affect the values for example:
int x[], y[];
myfile >> from[a];
for(int i=0; i<50;i++)
{
x[i] = from[i];
}
but it doesn't work. It seems that this way is only to read and display and a value in from will be deleted once another value comes.
Any help?
Thanks.
You're not incrementing your array index a in your loop. This results in line[0], to[0] and from[0] to be overwritten for every line in the file where contains_number returns true.
There is no reason for you to save your lines into memory. You can just process your lines as you go through the file (i.e. create a string line variable in your while loop).
Make sure you properly close your file handle.
Aside from that you should check your index bounds in the loop (a < 50), else you might be writing out of bounds of your arrays if your file has more numbers than 50.
A better solution yet would be to use vectors instead of arrays, especially if your file may contain any number of numbers.
Sorry if I am brief I had a lot of trouble putting this code up here.
I want to basically parse the file "question.txt"
and every time I see a period i want a new line
basically:
hey jim.(new line)
hey tim.(newline)
int main(){
ifstream openQuiz;
openQuiz.open("questions.txt");
string line;
//int count = 0;
//Check for errors
if (openQuiz.fail()) {
cerr << "Error opening file" << endl;
}
//Reading from beginning to ending;
while (!openQuiz.eof()) {
}
openQuiz.close();
return 0;
}
You could use an fstream instead of an ifstream. The difference is that fstreams can do input and output at the same time.
Then you could simply read the characters one by one. Whenever you read a '.' write a newline.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream f("file.txt");
char c;
while (f.get(c)) {
cout << c;
if (c=='.') cout << endl;
}
return 0;
}
How's this for you?
You can read more about std::istream::get() here http://www.cplusplus.com/reference/istream/istream/get/
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.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream& num, int (&array)[50]);
int main()
{
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if (file.fail()) {
cout << "The file failed to open.\n";
exit(1);
} else {
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return (0);
}
void make_array(ifstream& num, int (&array)[50])
{
int i = 0; // counter variable
while (!num.eof() && i < 50) {
num >> array[i];
i = i + 1;
}
for (i; i >= 0; i--) {
cout << array[i] << "\n";
}
}
I am trying to read values from a file to an array using fstream. When I try to display the contents of the array, I get 2 really big negative numbers, and then the contents of the file.
Any ideas what I did wrong?
Your use of num.get(array[i]) doesn't match any of its signatures. See get method description. What you want is this:
array[i] = num.get();
As discussed in the comments, you try to read an integer which is encoded as text. For this, you need to use operator>> (which reads any type encoded as string) instead of get (which reads a single byte):
num >> array[i];