my program ignores second loop and I can't fill vector v2
vector<int> v1;
vector<int> v2;
int elem1,elem2;
cout<<"Insert v1: ";
while(cin>>elem1){
v1.push_back(elem1);
}
cout<<"Insert v2: ";
while(cin>>elem2){
v2.push_back(elem2);
}
cin keeps going until all output is done, your 2nd loop is never gonna get hit unless you break from your first loop somehow. I would recommend you have some sort of exit condition on the first loop (such as some input marker like 'DONE' or something and once you read that you should break).
I'm guessing that you were expecting the first loop to end when you hit enter or something. but that's not what you coded. You coded 'fill up v1 until there is no input left', so it's not surprising that nothing ever gets put in v2.
Perhaps you could try the following, this reads one line, and put the contents in v1, it then reads a second line and puts the contents in v2. It uses getline to read a single line of text, then put that line into a string stream where you can read from one number at a time.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void fill_vector_from_one_line(vector<int>& v)
{
string str;
if (getline(cin, str))
{
istringstream iss(str);
int elem;
while (iss >> elem)
v.push_back(elem);
}
}
int main()
{
cout << "Insert v1: ";
fill_vector_from_one_line(v1);
cout << "Insert v2: ";
fill_vector_from_one_line(v2);
}
Apologies for any errors, I haven't checked this.
Reset standard input. See below.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v1;
std::vector<int> v2;
int elem;
std::cout << "Insert v1: ";
while (std::cin >> elem) {
v1.push_back (elem);
}
// Reset std::cin.
std::cin.clear();
std::cin.seekg(0, std::ios::beg);
std::cout << "Insert v2: ";
while (std::cin >> elem) {
v2.push_back (elem);
}
// Just to show that it works.
std::cout << "\nv1 elements:\n";
for (unsigned int ii = 0; ii < v1.size(); ++ii) {
std::cout << "v1[" << ii << "] = " << v1[ii] << "\n";
}
std::cout << "\nv2 elements:\n";
for (unsigned int ii = 0; ii < v2.size(); ++ii) {
std::cout << "v2[" << ii << "] = " << v2[ii] << "\n";
}
return 0;
}
Note that the std::cin.clear(); std:cin.seekg(); calls will have different behaviors depending on the nature of std::cin.
If std::cin is tied to the terminal it will have exactly the behavior that the OP is seeking.
If std::cin is reading from a file, vector v2 will be a carbon copy of vector v1.
If std::cin is reading from a pipe, vector v2 will be empty. You can't seekg() on a pipeline.
Related
I am a newbie in C++. I want to get user input by using a vector. I set the vector size of 5. However, I get the infinite loop in the for loop. Please let me know if there is something wrong. Thanks in advance.
int main() {
std::string name;
std::vector<std::string> stringVector (5);
for(int i = 0 ; i < stringVector.size(); i++)
{
std::cout << "Enter the name" << std::endl;
std::getline(std::cin, name);
stringVector.push_back(name);
}
}
std::vector<std::string>::push_back() inserts a new element i.e adds a new element and makes the size increase by one, hence you have an infinite loop. Note that you want the loop to stop after reaching the size iterations but the size increases for each iteration. You can use the following instead
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main() {
std::string name;
std::vector<std::string> stringsVector (5);
for(size_t i{} ; i < stringsVector.size(); i++)
{
std::cout << "Enter the name" << std::endl;
std::getline(std::cin, name);
stringsVector[i] = name;
}
std::for_each(stringsVector.cbegin(), stringsVector.cend(), [](auto & el){std::cout << el << " ";});
}
Demo
When using object size as 5 "stringsVector (5)" no need to use pushback, else it will increase the size of the object on every loop by 1
for easy understanding using simple for loop
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::string name;
std::vector<std::string> stringsVector (5);
for(size_t i= 0 ; i < stringsVector.size(); i++)
{
std::cout << "Enter the name" << std::endl;
std::getline(std::cin, name);
stringsVector[i] = name;
}
for(size_t i= 0 ; i < stringsVector.size(); i++)
{
std::cout << stringsVector[i] << " ";
}
}
after initialization of stringVector stringVector.size() = 5,
after each iteration the size is incremented by 1.
i is initialized with 0 and the condition (i < stringVector.size()) is always satisfied.
that's why You are getting infinite loop.
I am writing code that takes values from a user and stores it into a vector. The goal is that user can enter a said amount of values and they would be stored into a vector. The User will then be given the option to enter in another amount if he or she wishes and those values would also be stored in the same vector. However in order to terminate the inner while loop that allows the user to enter in the values, the user has to use EOF but that also ends my outer while loop. I do not know what a simple solution to this would be.
#include <iostream>
#include <vector>
#include<string.h>
using namespace std;
int main()
{
int a;
int holder, answer = 1;
vector<int> v;
vector<int> s;
while (answer == 1) {
cout << " Enter in a vector \n";
while (cin >> a) {
v.push_back(a);
}
s.insert(s.begin(), v.begin(), v.end());
for (int i{ 0 }; i < s.size(); i++) {
cout << s.at(i);
}
cout << " do you want to continue adding a vector? Type 1 for yes and 0 for no." << "\n";
cin >> holder;
if (holder == answer)
continue;
else
answer = 0;
}
return 0;
}
If the user closes his/her side of std::cin you won't be able to do cin >> holder; afterwards, so you need another way of letting the user stop entering numbers into the vector. Here's an alternative:
#include <iostream>
#include <vector>
#include <string> // not string.h
int main() {
int a;
int holder, answer = 1;
std::vector<int> v;
std::vector<int> s;
while(true) {
std::cout << "Enter in a vector of integers. Enter a non-numeric value to stop.\n";
while(std::cin >> a) {
v.push_back(a);
}
s.insert(s.begin(), v.begin(), v.end());
for(int s_i : s) {
std::cout << s_i << "\n";
}
if(std::cin.eof() == false) {
std::cin.clear(); // clear error state
std::string dummy;
std::getline(std::cin, dummy); // read and discard the non-numeric line
std::cout << "do you want to continue adding a vector? Type "
<< answer << " for yes and something else for no.\n";
std::cin >> holder;
if(holder != answer) break;
} else
break;
}
}
You could also take a closer look at std::getline and std::stringstream to make an even nicer user interface.
You might be better of using getline than cin. getline looks for \n instead of EOF as far as I remember,
But I have not used C++ in some time so I might be wrong about that.
http://www.cplusplus.com/reference/string/string/getline/
I'm trying to read and write some files, but i get "ERROR C1001, internal error happened in compiler" every time i try to std::cout something to my output.out file.
Why ?
(i used _CRT_SECURE_NO_WARNINGS in preprocesssor definition to be able to use freopen())
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <deque>
#include <array>
#include <vector>
freopen("C:\\somepath\\input.in", "r", stdin);
freopen("C:\\somepath\\output.out", "w", stdout);
int t;
std::cin >> t;
std::cout << t << std::endl;
for (int i = 0; i < t; i++)
{
int n;
std::cin >> n;
std::cout << t << std::endl;
std::vector <int> x, h;
x.resize(n);
h.resize(n);
for(int j=0;j<n;j++)
{
std::cin >> x[j] >> h[j];
std::cout<< x[j] << h[j] << std::endl;
}
}
EDIT : as Nighteen said, i had some errors in my code (n++, no vector resizing, now corrected)
But the bug, still there in some way :
The code is compiling in this state, but as soon as i try put cout a string, the same probleme appears
like adding <<" " in my std::cout<< x[j] << h[j] << std::endl;
in the std::cout<< x[j] <<" "<< h[j] << std::endl;
The code compiles fine in MSVC 15.5.2 assuming you put the code in a main block. Proof here.
Even though the compilation is OK, the code seems not to work out as it should. First of all, you can't std::cin >> x[j] >> h[j];. Create a temporary variable to store the input and then push it back into the vector:
int input1, input2;
std::cin >> input1 >> input2;
x.push_back(input1);
h.push_back(input2);
You should also note that this loop for (int j = 0; j < n; n++) never ends. The variable j should be increasing, not n. Whatever you are trying to achieve, this does not seem to be the way.
std::cout is a std::ostream used for outputting to the console. For outputting to files, used the classes std::ifstream and std::ofstream. Use the following syntax:
std::ifstream [ifstream_name](constructor parameters);
[ifstream_name] >> [container to store file contents];
std::ofstream [ofstream name](constructor parameters);
[ofstream_name] << [contents to write to 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';
}
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;
}