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.
Related
I try to read a .dat file with a list of coordinates X and Y. My code work to count the lines in the file but it doesn't work to read the coordinates correctly. In the output just show me the number of lines in the .dat file, but it doesn't show me the coordinates. .dat file has 2 column and more than 5 rows (I have many files with different amount of coordinates). Any help is super welcome, i am very new in C++.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
std::vector<int> numbers;
ifstream fileB;
const int SIZE=10;
char filas_dat [SIZE];
fileB.open("Verticesfixed_cell1slc44.dat");
std::string line;
int counter=0;
while (getline(fileB, line)) //contador de filas
{
++counter;
}
if(!fileB.good())
{
int current_number = 0;
while (fileB >> current_number){
numbers.push_back(current_number);}
fileB.close();
cout << "The numbers are: ";
for (int count = 0; count < numbers.size(); count++){
cout << numbers[count] << " ";}
cout << endl;
}
else
{
cout << "Error!";
}
return 0
}
The problem is that after you've counted the number of lines you are at the end of the file, so there is nothing more to read. A file doesn't reposition itself back to the beginning automatically. You have to tell the file to go back to the beginning.
A second similar problem is that when you get to the end of your file the getline function fails (because there's nothing more to read). That puts your file into an error state when nothing will work until you clear the error state.
Finally the call to !fileB.good() is unecessary. The file will never be good at this point, again this is because getline has failed.
Try this code
while (getline(fileB, line)) //contador de filas
{
++counter;
}
fileB.clear(); // clear the error state
fileB.seekg(0); // go back to the beginning of the file
int current_number = 0;
while (fileB >> current_number)
{
numbers.push_back(current_number);
}
I am having difficulty populating an array from a .txt file. I can do it without the while loop if I already know the size of the file. However, once I incorporate a while loop to extract the file size the input odes not configure correctly. Pleas take a look over my code an let me know if you see where I am going wrong.
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
int main()
{
using namespace std;
const char *inName_1 = "Instance_1.txt";
const char *inName_2 = "Instance_2.txt";
int arraySize_1 = 0, arraySize_2 = 0;
int array_1[20];
int array_2[20];
int number;
ifstream A2_file_1(inName_1);
if (A2_file_1.fail())
{
cout << "File 1 not open!" << '\n';
}
while (!A2_file_1.eof())
{
arraySize_1++;
A2_file_1 >> number;
}
if (A2_file_1.is_open())
{
for (int i = 0; i < arraySize_1; i++)
{
A2_file_1 >> array_1[i];
}
A2_file_1.close();
}
cout << "The size of the array 1 is: " << arraySize_1 << endl;
for (int i = 0; i < arraySize_1; i++)
{
cout << array_1[i] << endl;
}
return 0;
}
To read an arbitrary amount of numeric values from a text-file, all you need is an std::vector and a couple of std::istreambuf_iterator objects.
Then is as simple as
std::ifstream input("Instance_1.txt");
std::vector<int> values(std::istreambuf_iterator<int>(input),
std::istreambuf_iterator<int>());
That's it. Those four lines of code (counting the empty line) will read all int values from the text file Instance_1.txt and place them into the vector values.
#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];
Would like to fill an array one line at a time from the file "Hello.cpp". However if I do it the way below I fill the entire file [w] times instead of just grabbing one line from the file for each iteration of i.
If I remove the { } from getline then the array is filled with the last line of "Hello.cpp" [w] times.
I am not sure how to get a new [i] each time from the Hello.cpp file.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int w=0;
ifstream in("Hello.cpp");
string s;
while(getline(in, s))
w=w+1; //first count the number of lines in the file for the array
string a[w];//make an array big enough for the file
for(int i = 0; i < w ; i++) {
ifstream in("Hello.cpp");
string s;
while(getline(in, s)){
a[i] = s;
cout << i + 1 << " " << s << endl;
}
}
I would close your file before reopening it (best practice).
Looks to me like you need to move your file open (ifstream constructor) outside of your for (do you really want to open the file w times)? Since you bother to count the lines first don't you really want something like this:
ifstream in1("Hello.cpp");
for(int i = 0; i < w ; i++) {
getline(in1, a[i]);
cout << i + 1 << " " << a[i] << endl;
}
I am trying to read the two words "kelly 1000" in the text file "players", into vectors players and balances respectively. Don't know why it's not working?
string name = "kelly";
int main()
{
int num =0;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{
input_file >> players[num];
input_file >> balances[num];
num++;
}
for(size_t i = 0; i=players.size(); i++)
{
if(name==players[i])
cout << "Welcome " << name << ", your current balance is " << balances[i] << "$." << endl;
else
break;
}
With operator[] you can only access existing elements. Going out of bounds invokes undefined behaviour. Your vectors are empty and you need to use push_back method to add elements to them.
Second problem is while (!file.eof()) anti-pattern. It'll typicaly loop one to many times because the read of last record doesn't neccesarily trigger eof. When reading from streams, always check whether input succeeded before you make use of values read. That's typicaly done by using operator>> inside loop condition.
string temp_s;
int temp_i;
while (input_file >> temp_s >> temp_i) {
players.push_back(temp_s);
balances.push_back(temp_i);
}
This way the loop stops if operator>> fails.
//Hope this is something you want dear.Enjoy
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
string name = "kelly";
int main()
{
int num =0;
string tempname;
int tempbalance;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{ input_file>>tempname;
input_file>>tempbalance;
players.push_back(tempname);
balances.push_back(tempbalance);
}
for(size_t i = 0; i<players.size(); i++)
{
if(name==players.at(i))
cout<< "Welcome " << name << ", your current balance is " << balances.at(i)<< "$." << endl;
}
return 0;
}