Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C2039 error for string member function .pop_back() and .back()

Tags:

c++

string

stl

I am using and to program two functions that interchange between an integer and a string. The first function , string intToStr(int x), using :

1) std::basic_string::push_back

It works perfectly.

However, when the second function, int str2Int(const string &str), use the following member functions,

1) std::basic_string::pop_back
2) std::basic_string::back

I got the following errors:

1) error C2039: 'back' : is not a member of 'std::basic_string<_Elem,_Traits,_Ax>'  
2) error C2039: 'pop_back' : is not a member of 'std::basic_string<_Elem,_Traits,_Ax>'

The complete codes are below:

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;
string intToStr(int x)
{
    bool isNegative;
    int cnt = 0;
    if(x<0)
    {
        isNegative = true;
        x = -x;
    }
    else
    {
        isNegative = false;
    }

    string s;
    while(x)
    {
        s.push_back('0'+x%10);
        x /= 10;
        cnt ++;
        if(cnt%3==0 & x!=0)
            s.push_back(',');
    }


    if(isNegative)
        s.push_back('-');

    reverse(s.begin(),s.end()); //#include <algorithm>

    return s;

}

int str2Int(const string &str)
{
    int result=0, isNegative=0;
    char temp;
    string tempStr = str;
    reverse(tempStr.begin(),tempStr.end());

     // the following code snippet doesn't work??
     // pop_back() and back() are not member function??
    while(!tempStr.empty())
    {
        temp = tempStr.back(); 
        tempStr.pop_back();
        if(temp==',')
            continue;
        else if(temp=='-')
            isNegative = 1;
        else
            result = result*10 + (temp-'0');
    }

    return isNegative? -result:result;
}
like image 999
user2029505 Avatar asked Dec 05 '25 23:12

user2029505


1 Answers

These member functions are only present in C++11. You must compile your code as C++11 code in order for it to compile correctly.

The compiler that ships with Visual Studio 2008 does not support C++11. You will need to use a newer compiler.

You can use Clang, GCC, or upgrade to Visual Studio 2012.

like image 161
Dietrich Epp Avatar answered Dec 08 '25 13:12

Dietrich Epp