console application - C++ - Repeat std::getline() as user integer input? -


how repeat std::getline() user number input method:

  std::string num;   std::cout << "how many subjects want sum: ";   std::getline (std::cin,num); 

then take user number input , repeat std::getline() many times input sum subjects marks user input them after first questions.

prefer not use std::getline inputting numbers.

you need standard pattern:

int quantity = 0; std::cout << "enter quantity of subjects sum: "; std::cin >> quantity; int sum = 0; (int = 0; < quantity; ++i) {     int value;     std::cin >> value;     sum += value; } 

a common data input format specify quantity first number on single line.

the data follow on subsequent lines, 1 number per line.

the operator>> skip whitespace (including newlines).

edit 1: using getline
if must use getline, remember reads in strings (characters). if want numbers, have convert text representation internal representation.

int quantity; std::string text_line; std::cout << "enter quantity sum: "; std::getline(std::cin, text_line); int sum = 0; // extract number text {     std::istringstream text_stream(text_line);     text_stream >> quantity; } (int = 0; < quantity; ++quantity) {     std::getline(std::cin, text_line);     std::istringstream text_stream(text_line);     int value = 0;     text_stream >> value;     sum += value; } 

notice difference in number of lines.

also, notice usage of std::istringstream. looks using std::cin in first example.

there other techniques convert text representation of numbers internal representation. these left reader research.


Comments

Popular posts from this blog

Ansible warning on jinja2 braces on when -

Parsing a protocol message from Go by Java -

javascript - Replicate keyboard event with html button -