reading row from text file into two vectors c++ - c++

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;
}

Related

why does putting the data from a string varible into a string vector put every word into its own place in the vector -C++

im trying to get the data from a string variable and put it into its own place in a string vector but it saves each word as its own point in the vector.
i.e. "buy milk" will result in 0 being buy then 1 being milk not 0 being buy milk.
sorry for not knowing the proper terminology im really new to C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
vector <string> Notes;
int SaveNoteOnLine = 0;
string output; //a var needed for specific situations, not used for all output
cout << "welcome to cmdnotes alpha v1.0\n";
while (true) {
cin >> input;
if (input == "-list") {
for (int i = 0; i < SaveNoteOnLine; i++) {
cout << Notes.at(i) << endl;
}
}
else {
Notes.push_back(input);
cout << "saved on line " << SaveNoteOnLine << endl;
SaveNoteOnLine++;
}
}
}
Use
getline(cin,input) inplace of cin>>input it will take whitespaces as input

Interger representing a Array value is increasing within a for loop when trying to assign characters to a 2D Character array

in my program I am attempting to input characters from a .txt file and assign them to a 2D Char array to form a Maze. The expected outcome of this code is:
xxxxxxx
xA...Bx
xxxxxxx
However I am instead warned that Column is greater than size (defined as 30) when I believe it should be 0 at the start of every loop. No matter what Column is equal to Size and im not sure why. I've included the code below. I am beginner programmer so if you have any advice could you please make it as simple as possible.
Many thanks,
Ben
#include<fstream>
#include<iostream>
#include<string>
#include <vector>
//Maze Size
#define SIZE 30
using namespace std;
void readMaze(string fileName);
void inputMaze();
int main()
{
inputMaze();
}
void readMaze(string fileName)
{
int rows;
int columns = 0;
//vector<vector<char>> maze;
char maze[SIZE][SIZE];
ifstream input(fileName);
char data;
while (input.get(data)) //While loop used to store each individual data to the string.
{
for (int rows = 0; rows < 20; rows++)
{
columns = 0;
while (data != '\n')
{
if (rows > SIZE)
{
cout << "ROWS GREATER THAN SIZE";
break;
}
else if (columns > SIZE)
{
cout << "COLUMNS GREATER THAN SIZE";
break;
}
else
{
maze[rows][columns] = data;
columns++;
data = input.get();
}
}
data = input.get();
}
}
cout << "The Maze being solved is: " << endl;
cout << maze << endl;
input.close();
}
void inputMaze()
{
string userinput;
cout << "Plese input a .txt file name" << endl;
cin >> userinput; //User inputs the name of a .txt file --> goes to readMaze()
readMaze(userinput);
}
rows is used uninitialized in readMaze so the program has undefined behavior. Also, cout << maze << endl; makes the program have undefined behavior by reading out of bounds.
Consider making maze a std::vector<std::vector<char>> or even a std::vector<std::string> to make it simpler.
Example:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> readMaze(std::istream& input) {
std::vector<std::string> maze;
std::string line;
while(std::getline(input, line)) { // read a complete line at a time
maze.push_back(line); // and save it in the vector
}
return maze;
}
void inputMaze() {
std::string userinput;
std::cout << "Plese input a .txt file name\n";
if(std::cin >> userinput) {
std::ifstream is(userinput);
if(is) {
auto maze = readMaze(is);
std::cout << "The Maze being solved is:\n";
std::copy(maze.begin(), maze.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
// the file will be closed automatically when "is" goes out of scope
}
}
int main() {
inputMaze();
}

stock data from file into arrays c++

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.

printing weird symbols to output file, c++

I am writing a code that reads an input file of numbers, sorts them in ascending order, and prints them to output. The only thing printed to output is some really freaky symbols.
Here is my code
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i, y, temp, num[20];
char file_nameI[21], file_nameO[21];
ofstream outfile;
ifstream infile;
cout << "Please enter name of input file: ";
cin >> file_nameI;
infile.open(file_nameI);
if (!infile)
{
cout << "Could not open input file \n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> file_nameO;
outfile.open(file_nameO);
if (!outfile)
{
cout << "Could not open output file \n";
return 0;
}
for (i = 0; i < 20; i++)
{
y = i + 1;
while (y < 5)
{
if (num[i] > num[y]) //Correction3
{
infile >> temp;
temp = num[i];
num[i] = num[y];
num[y] = temp;
//y++; //Correction4
}
y++;
}
}
for (i = 0; i < 5; i++)
outfile << "num[i]:" << num[i] << "\n";
return 0;
}
Here is my input
6 7 9 0 40
Here is the output
 „Ô,üþ 54
H|À°ÀzY „Ô,üþ 0
Problems with your code are already mentioned in the comments but again:
First problem is uninitialized elements of num[20] - elements of num have indeterminate values so accessing any of them triggers undefined behavior. You should first read them from the file or at least initialize them to some default value.
The part of code that should most likely do the sorting is just completely wrong. If you'd like to implement your own function for sorting, you can pick up some well-known algorithm like e.g. quicksort - but C++ Standard Library already provides sorting function - std::sort.
Besides obvious mistakes:
You are using char[] - in C++ it's almost always better to use std::string.
Your static array can only store 20 values and you are reading those from a file. You can use std::vector which can grow when you add more elements than its current capacity. It also automatically fixes the problem with uninitialized elements of num[20].
As mentioned in the comments you can organize your code and improve readability by splitting it into functions.
Here you've got it quickly rewritten. This code uses std::string instead of char[], std::vector to store the numbers and std::sort. If there is something you don't understand here, read SO documentation:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> read_file(ifstream& in_file)
{
vector<int> vec;
int value;
while (in_file >> value)
{
vec.push_back(value);
}
return vec;
}
void write_file(ofstream& out_file, const vector<int>& values)
{
for (size_t i = 0; i < values.size(); ++i)
out_file << "value #" << i << ": " << values[i] << '\n';
}
int main()
{
string input_filename, output_filename;
ofstream out_file;
ifstream in_file;
cout << "Please enter name of input file: ";
cin >> input_filename;
in_file.open(input_filename);
if (!in_file)
{
cout << "Could not open input file\n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> output_filename;
out_file.open(output_filename);
if (!out_file)
{
cout << "Could not open output file\n";
return 0;
}
auto numbers = read_file(in_file);
sort(begin(numbers), end(numbers));
write_file(out_file, numbers);
return 0;
}
You might forgot to store values in num array. Just update your code as follows and it will work.
infile.open(file_nameI);
if (!infile){
cout << "Could not open input file \n";
return 0;
} else{
i = 0;
while (infile >> num[i]){
i++;
}
}

How to read txt file into vector and cout the file?

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> temp;
ifstream infile;
infile.open("numbers");
if (infile.fail())
{
cout << "Could not open file numbers." << "\n";
return 1;
}
int data;
infile >> data;
while (!infile.eof()) {
temp.push_back(data);
infile >> data;
}
cout << data << " " << endl;
}
I am simply trying to cout all the numbers from the text file "numbers" using a vector.
15
10
32
24
50
60
25
My experience is pretty much nil, and some guidance on why this fails to open would be very helpful.
Your code isn't working because you haven't attempted to print anything from the vector?
How do I print a vector?
Well first you have to understand how not to print a vector. The last line in your code, particularly this one:
cout << data << " " << endl;
is only printing out the last integer from the text file. In the loop where you performed the input, infile >> data overwrote each previous value of data and assigned it to the currently read value from the file. The result is that when the loop finishes, data will be equal to the last read value, particularly 25 looking at your file.
There's no overload for operator<<() that will allow you to do something like cout << temp, though you can implement one yourself. There exist several ways to print a vector, the easiest being a simple loop:
for (unsigned i = 0; i < temp.size(); ++i)
std::cout << temp[i] << " ";
Bonus: A faster way to print all the integers would be to print data from inside the loop. There's also the answer #KerrekSB made.
Your code is fine but you're printing the wrong thing.
Change the bottom of main to this
int data;
while (infile >> data) {
temp.push_back(data);
}
for( vector<int>::iterator i = temp.begin(); i != temp.end(); i++) {
cout << *i << endl;
}
*Edited after reading the suggested dup.
Try this:
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream infile("data.txt");
if (!infile) { /* error opening file */ }
for (int n : std::vector<int>(std::istream_iterator<int>(infile), {}))
{
std::cout << n << '\n';
}
}
Of course you don't need the vector if you just want to process the numbers:
for (std::istream_iterator<int> it(infile), end; it != end; ++it)
{
std::cout << *it << '\n';
}