-3

I am new to programming in C++. I am trying to ask the user an input (for example):

std::string numbers;
std::cout << What is your favorite number;
std::cin >> numbers

If the user entered

1, 2, 3

How do I extract only the number "2"? I know in python, you would do something like numbers[1], but is there a same way in C++ as well?

Kara
  • 765
  • 5
  • 11
  • 29

3 Answers3

3

So, "what are your favorite numbers?"

The idea is the same as in python or any other language: split the input line by the separator character, trim if you care, and finally get the element you want, if it exists.

Community
  • 1
  • 1
ShinTakezou
  • 9,432
  • 1
  • 29
  • 39
2

you can get the length of string by numbers.length().

then you can use for loop.

for(int i =0 ; i < numbers.length();i++)
{
  if(numbers[i] == '2')
     // do what you want you do here with 2
}

Keep in mind, your cin won't get entire "1, 2, 3" string because of whitespace. You should use getline instead of cin.

such as..

getline(cin, numbers,'\n'); 
thestar
  • 4,959
  • 2
  • 28
  • 22
1

To catch a line of numbers:

int main()
{
     std::vector<int>    numbers;
     std::string line;
     std::getline(std::cin, line);           // First read the whole line of input

     std::stringstream linestream(line);     // Set up to parse the line
     int               number;
     while(linestream >> number) {           // Read a number
        char x;                              // for the comma
        linestream >> x;                     // remove the comma

        numbers.push_back(number);           // Add to the vector (array)
     }

     // Print the number
     std::cout << "The second number is: " << numbers[1] << "\n";  // vectors are 0 indexed
}
Martin York
  • 257,169
  • 86
  • 333
  • 562