0

I am solving a basic problem but I am stuck. I don't use C++ but I must..

I am making a program that takes inputs (double) and does some mathematical operations (which are not important to this issue).

I need all inputs via CMD line. I know i can use this:

cin >> v1 >> v2 >> v3; //etc

But I dont know how many numbers the program will take. The program will stop when user sets a specific number.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
DoctorCZE
  • 51
  • 7
  • What do you mean you don't know how many numbers program take? Why do you insist on using one line? – Daffyd Oct 24 '15 at 17:19
  • Well, i try simply explain.. Example: Program make sum with input numbers. Program will stop only when user input 5 or 0 or someting specific. Becouse i dont know how many numbers will be. I know it is stupid thing for nothing but i need solve this. – DoctorCZE Oct 24 '15 at 17:37
  • I posted an answer that I think might be what you're looking for. It allows the user to input as many numbers as he wants, as long as they're separated by spaces, all in one line. – Daffyd Oct 24 '15 at 18:07
  • Welcome to Stack Overflow. I have fixed a few English issues with your post. Please explain (with data/numbers/code), as it is not clear what you are asking. – Rohit Gupta Oct 26 '15 at 20:35

2 Answers2

0

I see 2 possible solutions.

A. You can input std::string like this:

std::string input;
std::getline(std::cin, input);

That way you'll get whole string with inputs, then you can parse this string and get all data (search for whitespaces and so on);

B. You can use STL vector and make do\while cycle until something is received, like this:

std::vector<int> vec;
bool stop = false;

while (!stop) {
    int i;
    std::cin >> i;
    if (i == -1) { // for example -1 is "stop"
        stop = true;
    } else {
        vec.push_back(i);
    }
}

and then use vector for accessing and parsing data.

Starl1ght
  • 4,422
  • 1
  • 21
  • 49
0

Is the following similar to what you are looking for?

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    double num{ 0.0 }, specificNum{10.0};
    vector<double> vec(0);

    do {
        cout << "Enter number: ";
        cin >> num;
        vec.push_back(num);
    } while (!(abs(num - specificNum) < 0.5));

    system("pause");
    return 0;
}

The user is asked to enter a double until that double falls within +/- 0.5 of 10.0 (the specific number). You can decrease the range by lessening the number at the right side of the comparison. If we were dealing with integers, the comparison would have involved two values and not a range.

dspfnder
  • 1,135
  • 1
  • 8
  • 13