stringstream converter isn't working

Hey all,

So I'm a beginner at this and the concepts are a little hard for me to grasp. But anyway, I'm using a stringstream converter to turn the last 3 digits of the user's input to an integer so I can do proper checking validations with it. However, I can't seem to get my converter to work properly. Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<cstdlib>
#include<string>
#include<conio.h>
#include<sstream>

using namespace std;

int main()
{
    string temp;
    string custID;
    char pos1, pos2;
    int pos3;
    int custSize=5;
    int idLen;
    stringstream converter;
       cout << "Enter Customer ID: " << flush;
        cin >> custID;

        idLen = custID.length();

        for (int n = 0; n <= idLen-1; n++)
        {
            pos1=custID[0];
            pos2=custID[1];
            converter << custID;
            converter >> temp;
            pos3=atol(temp);


On the last 3 lines, I'm attempting to use the converter but the following error message occurs for the line pos3=atol(temp):

| error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'|


Thank you.
atol() is expecting a C-style string.
Use:
 
  pos3 = atol (temp.c_str());


Last edited on
But why are you even trying to use atol(), why not just extract the number to the proper type of variable in the first place? Converting a string to the different types is the main purpose of a stringstream.

If you would show your input and explain exactly what you're trying to do then maybe people would be more helpful.

Ex:
The user enters AB203

I want to check if that entry follows the following:
Starts with A, K, or S, followed by B, D, or E, followed by 188, 193, 200, or 260.

So for this I need to convert the last 3 positions into an integer so I can check properly with the switch statements I'm going to use.
Then since you're using a stringstream just use two character variables and a single integer variable.
1
2
3
4
5
6
7
string ID = "AB203";
char first_char, second_char;
int number;

stringstream sin(ID);

sin >> first_char >> second_char >> number;


Thank you so much!
Topic archived. No new replies allowed.