Home > Enterprise >  How do I access individual numbers in a string?
How do I access individual numbers in a string?

Time:05-01

Say I have a string that goes:

199  200  208  210  200  207  240  269  260  263

How do I make it so if that string is called s, then s[0] = 199 (rather than 1), s[1] = 200 (rather than 9), s[2] = 208 (rather than 9), etc. I am sorry to keep coming back here, but I really want to resolve this.

By the way, this is my code so far:

int main()
{
    int increase_altitude = 0;

    int previous = 10000;
    std::string s;
    while (std::getline(std::cin, s))
    {
        std::stringstream ss(s);
    }

CodePudding user response:

You can simply use vector of string for this purpose,

std::vector <std::string> numvec;
numvec.push_back("199");
numvec.push_back("200");

// accessing the element

numvec[0] // equals to 199

You can take input for the vector as:

std::string str;
for (int i = 0 ; i < 10000 ;   i){

    std::cin >> str;       // take input from the user  
    numvec.push_back(str); // add to the vector

}

However you would need to add vector header.

CodePudding user response:

This should be easily accomplished by doing this:

#include <vector>
#include <string>
#include <iostream>

int main()
{
    std::vector<std::string> sVect;
    std::string s;
    while (std::cin >> s)
       sVect.push_back(s);
}

There is no need to hardcode any values into a for loop, as the while will terminate when there is no more input to process.

  •  Tags:  
  • c
  • Related