I have a qns. How can i take out the number in a basic string input and assign them into different integer variable? Not a file input

example - string input = "23/4/56" or "23.4.56"

int a = 23, b=4, c = 56

#include <iostream>
#include <string>
using namespace std;

string digit1, digit2, 

int main()
{

    string value;
    cout <<"Please input something: ";
    cin >> value;
     
       for(int i=0; i<value.size(); i++) 
       if(value[size] != '/' ||value[size] != '.')
          if (isdigit(value[size])))
            digit1 +=value[size]; 
          else    
          ??
    cout << endl;
    return 0;
}

This may help you out with converting string literals to numbers.

Chris

Hi

here a solution to your problem:

#include <iostream>
using namespace std;

class myExpression
{
	public:
		friend ostream& operator<<(ostream&,myExpression&);
		friend istream& operator>>(ostream&,myExpression&);
	
		int firstNumber;
		int secNumber;
		int thirdNumber;
};

ostream& operator<<(ostream& out ,myExpression& exp)
{
	if(!cin.fail())
		cout<<"{"<<exp.firstNumber<<","<<exp.secNumber<<","
						<<exp.thirdNumber<<","
						<<"}"<<endl;
	else
		cout<<"\nInvalid Data"<<endl;
	return out;
}

istream& operator>>(istream& i ,myExpression& exp)
{
	if(cin.peek()!='{')
		cin.clear(ios::failbit);
	else
		i.ignore();
	
	cin>>exp.firstNumber;
	
	if(cin.peek()!=',')
		cin.clear(ios::failbit);
	else
		i.ignore();

	cin>>exp.secNumber;
	
	if(cin.peek()!=',')
		cin.clear(ios::failbit);
	else
		i.ignore();
	
	cin>>exp.thirdNumber;
	
	if(cin.peek()!='}')
		i.ignore();
	else
		cin.clear(ios::failbit);
	
	return i;
}

int main()
{
	int a=0;
	int  b=0;
	int c= 0;
	myExpression expr;
	cout<<"Enter the expresion: {a,b,c}"<<endl;
	cin>>expr;
	a=expr.firstNumber;
	b=expr.secNumber;
	c=expr.thirdNumber;
	
	cout<<"first number of expression is: "<<a<<endl;
	cout<<"second number of expression is: "<<b<<endl;
	cout<<"third number of expression is: "<<c<<endl;
	
	return 0;
}

of course u can make some small changes....:D
to have it in the "1,2,3" format....

>here a solution to your problem
That is a very long and overcomplex solution to his problem I think :) Heres my solution.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
   string value;
   cout << "Please input something: ";
   getline(cin, value);

   vector<int> numbers;
   int temp = 0;

   for (size_t i = 0;; ++i)  {
      if (isdigit(value[i])) {
         temp *= 10;
         temp += value[i] - '0';
      } else {
         numbers.push_back(temp);
         temp = 0;
      }
      if (value[i] == 0) {
         break;
      }
   }

   for (size_t i = 0; i < numbers.size(); ++i) {
      cout << "Number " << (i+1) << ": " << numbers[i] << endl;
   }

   cin.ignore();
   return 0;
}

There are (at least) two defects in this short solution:
1. Try to type "HowManyPhantomZeroesPushed:1-2-3-4-5..."...
2. Strictly speaking, the last char of std::string value is not equal to 0. Index value must be less that value.length(). Declare a const char pointer initialized by value.c_str().

>the last char of std::string value is not equal to 0.
Yes it is :icon_neutral: It is the null terminator, every std::string finishes with one.

And, try typing "HowManyPhantomZeroesPushed:1-2-3-4-5..." in the longer solution, I can assure you it isn't much better :)

It is the null terminator, every std::string finishes with one.

Alas, it's a wrong statement. Don't mix C-string convention, std::string definition by the C++ Standard and c_str() member function functionality.

I don't discuss "long solution" now and here. There is an obvious defect in YOUR solution. If a string does not started from a digit, your parsing is wrong - that's all.

Thx for the reply. Given that, how can i limit the user to only enter string like {2,3,4,5}.

You can't forbid a user to type what he/she wants. But your program can reject bad input and ask retyping. Add a proper code...

ok..Can you guide me on this?

OK... That's pseudocode:

loop
    prompt
    input
    if input ok then
       save
       break
    else
         try again message
    endif
endloop

Is this the correct way?

string str;


cout <<"Enter an input string:" << endl;
cin >> str;


 for(int i=0; i<str.length(); i++)
 {
    if((str[0] == '{') && (str[str.length()-1] == '}'))
     // how do i check the commas and take out the variable?   
   else    
    cout<<"Invalid format!" <<endl; 

}

Is this the correct way?

Starting to look like it :)

Next you'll have to figure out how to split the string into numbers and discard the comma's. So you'll need a sort of tokenizer .

Since you don't know how many numbers are in the input string, you should use a vector<int> to store the numbers in. That way you won't have to worry about array-bounds.

You'll also need a function to convert string->int, and it's you lucky day because here's one:

#include <sstream>
[...]

int StringToInt(string Input)
{
	istringstream conv(Input);
	int number = 0;
	conv >> number;
	return number;
}

I searched and found substr() function. Can you guide me on how to use this function for my problem?

May be it helps to taste fast scanner codes in C++ ;) :

/// No cctype & macro/func dependency
inline bool isDigit(char c) {
    return c >= '0' && c <= '9';
}
/// For C-strings
/** Check for {d...,...,d...} pattern */
bool isUList(const char* p)
{
    if (p != 0 && *p++ == '{')
    while (isDigit(*p++)) { // at least 1 digit
        while (isDigit(*p)) // skip digits
            ++p;
        switch (*p) {
        case ',':
            ++p; continue;
        case '}':
            return *(p+1) == '\0';  // eos?
        default:
            return false;
        }
    }
    return false;
}

inline // For std::string argument
bool isUList(const std::string& s) {
    return isUList(s.c_str());
}

Look at the modification for patterns like {int,...,int}:

/// For {intnum,...,intnum} pattern
bool isSList(const char* p)
{
    if (p != 0 && *p++ == '{')
    for (;;)
    {
        if (*p == '+' || *p == '-')
            ++p;
        if (!isDigit(*p++)) // at least 1 digit
            break;
        while (isDigit(*p)) // skip digits
            ++p;
        switch (*p) {
        case ',':
            ++p; continue;
        case '}':
            return *(p+1) == '\0';  // eos?
        default:
            return false;
        }
    }
    return false;
}
inline bool isSList(const std::string& s) {
    return isSList(s.c_str());
}

Try this:

int main()
{
    std::string s;
    std::cout << "Enter {ddd,...,ddd} or Ctrl+Z to quit." 
        << std::endl;
    while (std::cout<<'>',std::getline(std::cin,s))
        std::cout << (isUList(s)?"OK":"Fail") << std::endl;
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.