Reputation: 1
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);
}
}
Upvotes: 0
Views: 306
Reputation: 1
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.
Upvotes: 0
Reputation: 1
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] << " ";
}
}
Upvotes: 0
Reputation: 7100
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 << " ";});
}
Upvotes: 1