Hello!
I'm a c++ beginner, so to learn the language, I watch tutorials online or make up some program and try to advance it as much as possible.
So, I wanted to create a program that will ask the user for how many people is in his group, and then asks him to input the names of the people in the group.
It's far from finished, but I ran into a problem.
I have an if statement (ln. 24), to make sure the input from the user is valid and to make sure he can't enter more than 1000 people.
This works all fine, unless the user enters a letter.
eg. the user inputs the letter "h", the program crashes and a an error box says: "Unhandled exception at 0x7786DAD8 in Vectors.exe: Microsoft C++ exception: std::length_error at memory location 0x0018FBAC."
Any help on this, would be much appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
// Vectors.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <limits>
int main()
{
//Define variables needed for program.
unsigned int numOfPeople;
std::string name;
double long l;
//Asks the user for input
std::cout << "Please enter the number of people in your group: ";
std::cin >> numOfPeople;
//Tests if user input is valid.
if (std::cin.fail() || numOfPeople > 1000 ) {
std::cout << "Please enter the number of people in your group: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin >> numOfPeople;
}
//Creates the vector
std::vector<std::string> peopleInGroup;
//Sets the size of the vector from numOfPeople
peopleInGroup.reserve(numOfPeople);
//Asks the user to input the name(s)
std::cout << "Enter a name, then hit enter, to enter the next name: ";
for (int x = 0; x <= numOfPeople; x++) {
getline(std::cin, name);
peopleInGroup.push_back(name);
std::cin.clear();
}
std::cout << "The people in your group are: ";
for (int x = 0; x <= numOfPeople; x++) {
std::cout << peopleInGroup[x] << "\n";
}
system("PAUSE");
return 0;
}
|