Xstring c error

I've been creating a class that defines an integer in a base other than ten. Today when I tried to compile I got a long list of errors in xstring which seemed to mostly be undefined type errors or

I’ve been creating a class that defines an integer in a base other than ten. Today when I tried to compile I got a long list of errors in xstring which seemed to mostly be undefined type errors or undeclared identifier errors. I was wondering if this is a result of forgetting to include some file or me misusing a string.

intBase.cpp (the class where I would have mishandled a string)

#include "intBase.h"

intBase::intBase(int b)
{
    base = b;
    num = 0;
}

intBase::intBase(std::string n, int b)
{
    base = b;
    setNum(n);
}

int intBase::getBase() const
{
    return base;
}

void intBase::setBase(int b)
{
    base = b;
}

std::string intBase::getNum() const
{
    int expo = 0, n, numTemp = num;
    std::string result = "";
    char ch;

    while (num > int(pow(base, expo)))
    {
        expo++;
    }
    expo--;

    while (expo >= 0)
    {
        n = int(numTemp / pow(base, expo));
        ch = convert(n, false);
        numTemp -= int(n * pow(base, expo));
        result += ch;
        expo--;

    }

    return result;
}

void intBase::setNum(std::string n)
{
    char ch;
    int expo, temp;

    num = 0;
    expo = 0;

    while (n.size() > 0)
    {
        ch = n[n.size() - 1];
        temp = convert(ch, true);
        num += int(temp * pow(base, expo));
        expo++;
        n = n.substr(0, n.size() - 1);
    }

}

int intBase::getNumTen() const
{
    return num;
}

void intBase::setNumTen(int n)
{
    num = n;
}

intBase intBase::add(const intBase& iBase) const
{
    intBase IB(1);

    if (getBase() > iBase.getBase())
    {
        IB.setBase(base);
    }
    else
    {
        IB.setBase(base);
    }

    IB.setNumTen(getNumTen() + iBase.getNumTen());

    return IB;
}

intBase intBase::operator+(const intBase& iBase) const
{
    return add(iBase);
}

std::ostream& operator<<(std::ostream& output, const intBase& iBase)
{
    output << iBase.getNum();
    return output;
}

// takes a character and returns its base ten conversion if bool is true
// takes a base-ten integer and returns its character conversion if bool is false
int intBase::convert(int x, bool letter) const
{
    int result;

    if (letter)
    {
        if (x >= 48 && x <= 57)
            result = x - 48;
        else if (x >= 97 && x <= 122)
            result = x - 87;
        else if (x >= 65 && x <= 90)
            result = x - 29;
        else
            result = -1;
    }
    else
    {
        if (x >= 0 && x <= 9)
            result = x + 48;
        else if (x >= 10 && x <= 35)
            result = x + 87;
        else if (x >= 36 && x <= 61)
            result = x + 29;
        else
            result = -1;
    }

    return result;
}

intBase.h

#pragma once
#include <string>
#include <cmath>

class intBase
{
public:
    intBase(int b);
    intBase(std::string n, int b);

    int getBase() const;
    void setBase(int b);
    std::string getNum() const;
    void setNum(std::string n);
    int getNumTen() const;
    void setNumTen(int n);

    intBase add(const intBase& iBase) const;
    intBase operator+(const intBase& iBase) const;

    friend std::ostream& operator<<(std::ostream& output, const intBase& iBase);

private:
    int convert(int x, bool y) const;
    int num, base;
};

test.cpp

#include <iostream>
#include "intBase.h"
#include <string>
using namespace std;

int main()
{
    int base;
    string numTemp;

    cout << "enter the base of your number: ";
    cin >> base;
    intBase num(base);

    cout << "enter a number in base " << base << ": ";
    cin >> numTemp;
    num.setNum(numTemp);

    cout << num.getNumTen() << endl;
    cout << num << endl;
    cout << num + num << endl;

    system("pause");
    return 0;
}

error log

1>------ Build started: Project: numBaseTest, Configuration: Debug Win32 ------
1>intBase.cpp
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(435,23): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(4519): message : see reference to function template instantiation 'std::basic_ostream<char,std::char_traits<char>> &std::_Insert_string<char,std::char_traits<char>,unsigned int>(std::basic_ostream<char,std::char_traits<char>> &,const _Elem *const ,const _SizeT)' being compiled
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(4519): message :         with
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(4519): message :         [
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(4519): message :             _Elem=char,
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(4519): message :             _SizeT=unsigned int
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(4519): message :         ]
1>E:collegenumBaseTestnumBaseTestnumBaseTestintBase.cpp(104): message : see reference to function template instantiation 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<char,std::char_traits<char>,std::allocator<char>>(std::basic_ostream<char,std::char_traits<char>> &,const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)' being compiled
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(435,1): error C2065: 'iostate': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(435,31): error C2146: syntax error: missing ';' before identifier '_State'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(435,31): error C2065: '_State': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(435,49): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(435,1): error C2065: 'goodbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(438,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(441,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(444,29): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(444,1): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(444,36): error C2146: syntax error: missing ';' before identifier '_Ok'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(444,36): error C3861: '_Ok': identifier not found
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(446,10): error C2065: '_Ok': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(447,9): error C2065: '_State': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(447,28): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(447,1): error C2065: 'badbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(450,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(450,39): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(450,1): error C2065: 'adjustfield': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(450,64): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(450,1): error C2065: 'left': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(452,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(452,1): error C2660: 'std::_Narrow_char_traits<char,int>::eq_int_type': function does not take 1 arguments
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(401,38): message : see declaration of 'std::_Narrow_char_traits<char,int>::eq_int_type'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(453,21): error C2065: '_State': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(453,40): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(453,1): error C2065: 'badbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(459,13): error C2065: '_State': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(459,32): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(459,1): error C2065: 'goodbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(460,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(461,13): error C2065: '_State': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(461,32): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(461,1): error C2065: 'badbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(464,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(464,1): error C2660: 'std::_Narrow_char_traits<char,int>::eq_int_type': function does not take 1 arguments
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(401,38): message : see declaration of 'std::_Narrow_char_traits<char,int>::eq_int_type'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(465,21): error C2065: '_State': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(465,40): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(465,1): error C2065: 'badbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(471,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(472,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(472,9): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(472,1): error C2065: 'badbit': undeclared identifier
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(475,1): error C2027: use of undefined type 'std::basic_ostream<char,std::char_traits<char>>'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includeiosfwd(216): message : see declaration of 'std::basic_ostream<char,std::char_traits<char>>'
1>test.cpp
1>Generating Code...
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.23.28105includexstring(475,20): error C2065: '_State': undeclared identifier
1>Done building project "numBaseTest.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Thank you for all your help in advance.

this is my code.. but i get error in xstring header file at this part
size_type size() const
{ // return length of sequence
return (this->_Mysize);
}

here’s my full code:

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

struct node
{
string title;
string artist;

node* right;
node* left;
};

class song
{
private:
node *root;
node *insertx(string song,string artist,node *xyz)
{
if(song<xyz->title)
{
if(xyz->left==NULL)
{
xyz->left=new node;
xyz->left->left=NULL;
xyz->left->title=song;
xyz->left->artist=artist;
xyz->left->right=NULL;
}
else
{
insertx(song,artist,xyz->left);
}

}
else if(song>xyz->title)
{
if(xyz->right==NULL)
{
xyz->right=new node;
xyz->right->left=NULL;
xyz->right->title=song;
xyz->right->artist=artist;
xyz->right->right=NULL;
}
else
{
insertx(song,artist,xyz->right);
}

}
return xyz;
}
node *searchbytitle(string song,node *xyz)
{
if(song==xyz->title)
{
return xyz;
}
else if(song<xyz->title)
{
if(xyz->left!=NULL)
{
searchbytitle(song,xyz->left);
}
else
{
return NULL;
}
}
else if(song>xyz->title)
if(xyz->right!=NULL)
{
searchbytitle(song,xyz->right);
}
else
{
return NULL;
}

}
void deletesong(string song,node *xyz)
{
node*a;
a=new node;
if(song==xyz->title)
{
xyz->left=a;
xyz->left->left=a->left;
xyz->left->artist=a->artist;
xyz->left->title=a->title;
delete xyz;

}
else if(song<xyz->title)
{
deletesong(song,xyz->left);
}
else if(song>xyz->title)
{
deletesong(song,xyz->right);
}
cout<<«DELETED!!! n «;

}
void searchbyartist(string artist,node *xyz)
{
node*temp;
temp=new node;
temp=root;
while(temp->left!=NULL)
{
if(artist==temp->artist)
{
cout<<temp->title<<endl;
}
temp=temp->left;
}
while(temp->right!=NULL)
{
if(artist==temp->artist)
{
cout<<temp->title<<endl;

}
temp=temp->right;
}
}
public:
song(){root=NULL;}
node* insert(string song,string artist)
{
node*temp;
temp=new node;
if (root==NULL)
{
root=new node;
root->artist=artist;
root->title=song;
root->left=NULL;
root->right=NULL;
temp=root;
}
else
{
temp= insertx(song,artist,root);
}
cout<<«nnSong added to the library n»;
return temp;
}
node* titlesearch(string song)
{
node *temperory;
temperory=new node;
if (song==root->title)
{
return root;
}
else
{
temperory=searchbytitle(song,root);
return temperory;
}
}
void artistsearch(string artist)
{
searchbyartist(artist,root);
}
void deletesongs(string song)
{
deletesong(song,root);
}
void display(node* data)
{
node *datax;
datax=new node;
datax=data;
while(data->left!=NULL)
{
data=data->left;
cout<<data->title<<setw(7)<<data->artist<<endl;
}
while(datax->right!=NULL)
{
datax=datax->right;
cout<<datax->title<<setw(7)<<datax->artist<<endl;
}
}
};

void menu()
{
song x;
node *temp;
temp=new node;
int a=0;
string title=»»;
string artist=»»;
cout<<«****WELCOME TO YOUR MUSIC LIBRARY****n Please Pick One Of Following Options -: n»;
cout<<«1)Add a New Song n2)Search a Song n3)Delete a song n4)Display Your Music Databasen»;
cin>>a;
if (a==1)
{
cin.ignore();
cout<<«nnPlease Enter New Song’s Title n»;
getline(cin,title);

cout<<«nnPlease Enter it’s Artist’s name n»;
getline(cin,artist);
cin.ignore();
temp=x.insert(title,artist);
}
else if (a==2)
{

int c=0;
cout<<«**Enter 1 for searching by song’s title n»;
cout<<«**Enter 2 for searching by song’s artist n»;
cin>>c;
if(c==1)
{
node*d;
d=new node;
cout<<«Enter Song’s title n»;
cin.ignore();
getline(cin,title);
d=x.titlesearch(title);
cout<<d->title<<» «<<d->artist<<endl;
}
else if(c==2)
{
cout<<«Enter Artist Name n»;
cin.ignore();
getline(cin,artist);
x.artistsearch(artist);

}
else
{
cout<<«***ERROR***WRONG CHOICE INPUT***n»;
}
}
else if (a==3)
{
cout<<«Enter song’s name n»;
getline(cin,title);
x.deletesongs(title);
cout<<endl;
}
else if(a==4)
{
x.display(temp);
}
int f=0;

cout<<«nnPress 1 to Continue Managing Library n»;
cin>>f;
if(f==1)
{
menu();
}
}

int main()
{
menu();
return 0;
}

PLZZ help as i need it to work very urgent.. thanks

  • Remove From My Forums
  • Question

  • Please help.
    I can’t compile my file with <string>. Here is the code:

    #include <cstdlib>
    #include <string>

    int xxx()
    {    string my_str;
        return 0;
    }

    The error:
    1>—— Build started: Project: teststring, Configuration: Debug Win32 ——
    1>Compiling…
    1>teststring.cpp
    1>c:program filesmicrosoft visual studio 9.0vcincludexstring(17) : error C2143: syntax error : missing ‘;’ before ‘namespace’
    1>c:program filesmicrosoft visual studio 9.0vcincludexmemory(171) : error C2804: binary ‘operator ==’ has too many parameters
    1>        c:program filesmicrosoft visual studio 9.0vcincludexstring(17) : see reference to class template instantiation ‘std::allocator<_Ty>’ being compiled
    1>c:program filesmicrosoft visual studio 9.0vcincludexmemory(178) : error C2804: binary ‘operator !=’ has too many parameters
    ……

    Line 13 in xstring is «_STD_BEGIN»

    I am lost for good. Please help. Thanks

Answers

  • Well, for starters you need std namespace for string:

    #include <cstdlib>
    #include <string>

    int xxx()
    {   
        std::string my_str;
        return 0;
    }


    David Wilkinson | Visual C++ MVP

    • Marked as answer by

      Tuesday, October 7, 2008 6:52 AM

  • You also need to name your file with a .cpp extension.  While unixy systems may use .C for C++ code, Windows is case-insensitive and that will result in compiling using the C89 rules (hence the error using the keyword ‘namespace’).

    • Marked as answer by
      Yan-Fei Wei
      Tuesday, October 7, 2008 6:52 AM

  • Review your actual list of #includes and check the first one that’s yours and is #included before the header that gives the error message.  Make sure all your class declarations are properly terminated with a semi-colon, start at the bottom.   For example:

    class Test {
      // blabla
      //…
    }  // <— Missing semi-colon


    Hans Passant.

    • Marked as answer by
      Yan-Fei Wei
      Tuesday, October 7, 2008 6:52 AM

#c

#c

Вопрос:

Я начинающий программист на C . Я пытаюсь создать программу, которая регистрирует пользователя в программе, все скомпилировано идеально, но когда я пытаюсь ее запустить, я получаю ошибку Xstring, в которой говорится, что это было 0x7FF6F0AACFF0 «.

Я полагаю, что ошибка могла быть вызвана тем фактом, что я очень новичок в использовании файлов в коде, и мне нужно было использовать их в этой программе, поскольку они были единственным способом постоянного сохранения данных для входа и пароля.

Я переписывал этот проект более 5 раз, и на данный момент это самый функциональный вариант. Я попытался использовать ofstream и ifstream , но отказался от них, потому что для каждого файла был сохранен только один пароль и логин; поэтому я думаю, что основная ошибка, вероятно, содержится в функциях Processing и Array_filler , все, что мне нужно, это указать правильное направление, и я, вероятно, смогу ее устранить.

C :

 #include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;

//bug_1 need to fix the error where the code doesn't recognize a returning user
//Project_1 need to implement a subsystem that recommends a random password amp; Login 
//Project_2 need to implement a subsystem that requires a strong password

string Word_blip[90] = {};
string Pass_blop[90] = {};
string password;
string logWord;
string Login_1;
string Pass_1;
int KILL_SWITCH = 1;
int y = 0;
void Array_filler();
void Start_up();
void Yupper_pupper();
void processing();
void New_Login();

int main() {
    Start_up();
    if (KILL_SWITCH == 0) {
        return EXIT_SUCCESS;
    }
    Yupper_pupper();
    processing();
}

void Start_up() {
    Array_filler();
    cout << "Login:";
    cin >> logWord;
    cout << "Password:";
    cin >> password;
    for (y; y >= 90; y  ) {
        cout << "Preparing" << endl;
    }
    system("cls");
    if (Word_blip[y] == logWord) {
        cout << "Login accepted, welcome user:" << endl;
    } else if (Word_blip[y] != logWord) {
        New_Login();
    }
}

void New_Login() {
    string i_1_5;
    cout << "Login not recognized, would you like to sign up?" << endl;
    cin >> i_1_5;
    if (i_1_5 == "yes") {
        void Yupper_pupper();
    } else if (i_1_5 == "no") {
        cout << "Have a good day!" << endl;
        KILL_SWITCH = 0;
    } else {
        cout << "That's not a valid answer ;-) please retry" << endl;
        New_Login();
    }
}

void Yupper_pupper() {
    system("cls");
    cout << "Please Sign in with your new username amp; Password." << endl;
    cout << "New Login:";
    cin >> Login_1;
    cout << "New password:";
    cin >> Pass_1;
    void processing();
}

void processing() {
    /* acts like "ofstream" or "ifstream combined; with the
    ios::in and ios::out replacing the sort of "read out file" 
    ofstream meant with "ios::in"and the "input into file" that 
    ifstream provided with ios::out*/
    fstream Urfile("Logins.txt", ios:: in );
    string Placeholder_1;
    if (Urfile.is_open()) {
        getline(Urfile, Placeholder_1);
        /* While Urfile = "While the file is open" Urfile = true
        When the file runs out of information the file will close 
         making the statement false and ending the loop ;-)*/
        while (Urfile) {
            Placeholder_1 = Word_blip[0];
        }
        Urfile.close();
    } else {
        cout << "ERROR_OPENING_URFILE_ABORTING_PROGRAM_1" << endl;
        abort();
    }
    fstream Myfile("Passwords.txt", ios:: in );
    string Placeholder_2;
    if (Myfile.is_open()) {
        getline(Myfile, Placeholder_2);
        while (Myfile) {
            Placeholder_2 = Pass_blop[0];
        }
        Myfile.close();
    } else {
        cout << "ERROR_OPENING_MYFILE_ABORTING_PROGRAM_1" << endl;
        abort();
    }
    Start_up();
}

void Array_filler() {
    /*This function is responsible for clearing out the file
    and replacing everything inside with the contents of Pass_blip and Word_blop
    . Don't worry! none of the data will be lost because it was all written to the
    arrays to be processed alongside the new inputs*/
    fstream Urfile("Login.txt", ios::out);
    if (Urfile.is_open()) {
        for (int i = 0; Word_blip[i] != "n"; i  ) {
            Urfile << Word_blip[i] << endl;
        }
        Urfile.close();
    } else {
        cout << "ERROR_OPENING_URFILE_ABORTING_PROGRAM_2" << endl;
        abort();
    }
    fstream Myfile("Passwords.txt", ios::out);
    if (Myfile.is_open()) {
        for (int i = 0; Pass_blop[i] != "n"; i  ) {
            Myfile << Pass_blop[i] << endl;
        }
        Myfile.close();
    } else {
        cout << "ERROR_OPENING_MYFILE_ABORTING_PROGRAM_2" << endl;
        abort();
    }
}
 

Комментарии:

1. void Yupper_pupper(); это объявление функции, а не вызов функции. Не используйте void при вызовах функций.

2. Ах да, я понимаю, что вы имеете в виду. Спасибо!

3. Просто чтобы уточнить, я провел некоторое тестирование и обнаружил, что ошибка определенно связана с функцией Arrayfiller.

Я работаю над учебным пособием по изучению C ++ с использованием самой последней версии Visual Studio Community 2017 в обновленной версии Windows 8.1.

Когда я настроил следующий файл .cpp и запустил программу, он потерпел крах после ввода ввода с ошибкой:

Ошибка отладки!

Программа C: WINDOWS SYSTEM32 MSVCP140D.dll Файл c: program files (x86) microsoft visual studio 2017 community vc tools msvc 14.11.25503 include xstring
Линия: 2969

Строковый индекс выражения находится вне диапазона

#include "stdafx.h"#include "FBullCowGame.h"
using int32 = int;

FBullCowGame::FBullCowGame() { Reset(); }

int32 FBullCowGame::GetMaxTries() const { return MyMaxTries; }
int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; }

void FBullCowGame::Reset()
{
constexpr int32 MAX_TRIES = 8;
MyMaxTries = MAX_TRIES;

const FString HIDDEN_WORD = "ant";
MyHiddenWord = HIDDEN_WORD;

MyCurrentTry = 1;
return;
}bool FBullCowGame::IsGameWon () const { return false; }

bool FBullCowGame::CheckGuessValidity(FString)
{
return false;
}
// Receives a VALID guess, increments turn, and returns count

FBullCowCount FBullCowGame::SubmitGuess(FString Guess)
{
// incriment the turn number
MyCurrentTry++;

// setup a return variable
FBullCowCount BullCowCount;

// loop through all letters in the guess
int32 HiddenWordLength = MyHiddenWord.length();
for (int32 i = 0; i < Guess.length(); i++) {
// compare letters against the hidden word
for (int32 j = 0; j < HiddenWordLength; j++) {
// if they match then
if (Guess[j] == MyHiddenWord[i]) {
if (i == j) { // if they're in the same place
BullCowCount.Bulls++; // incriment bulls
}
else {
BullCowCount.Cows++; // must be a cow
}
}
}
}
return BullCowCount;
}

При отладке это привело меня к строке, указанной в xstring, это дает следующую ошибку:

Необработанное исключение в 0x100управляемом F6 (ucrtbased.dll) в BullCowGame.exe: недопустимый параметр был передан функции, которая считает недопустимые параметры фатальными.

для кода:

    reference operator[](const size_type _Off)
{   // subscript mutable sequence
auto& _My_data = this->_Get_data();
_IDL_VERIFY(_Off <= _My_data._Mysize, "string subscript out of range");
return (_My_data._Myptr()[_Off]);
}

Кажется, есть точки останова, вызванные чем-то, что я сделал, но код отражает код в учебнике, и код учебника компилируется и работает правильно.

Кто-нибудь знает, как с этим бороться? Я иду пустым на поиски.

1

Решение

Это выглядит очень подозрительно:

for (int32 i = 0; i < Guess.length(); i++) {
// compare letters against the hidden word
for (int32 j = 0; j < HiddenWordLength; j++) {
...

Обратите внимание, я ограничен длиной догадки, и J ограничено длиной HiddenWord.

Обратите внимание, что вы перепутали свои индексные переменные здесь:

        // if they match then
if (Guess[j] == MyHiddenWord[i]) {

Кроме того, вы все равно должны были смотреть на эту строку, так как исключение было в operator [], и это единственное место в опубликованном вами коде, в котором используется рассматриваемый оператор … 🙂

0

Другие решения

Других решений пока нет …

Если убрать двойной уровень вложенности, и классы, то по факту, Вы хотите написать вот такой код

std::string s{0};

(да да, фигурные скобки «универсальной инициализации» обычно «очень жестоки» при несоответствии типов, но ноль это отдельная тема).

Этот код выглядит интересно, но он полулегален. Дело в том, что 0 в с++ по наследству от с конвертируется в NULL / nullptr.

У строки (а точнее у basic_string) есть конструктор, который принимает указатель на строку (что бы программист мог написать вот так вот

std::string s = "test";

)

Но компилятор не всегда может отличить указатель на строку от nullptr (по факту можно сделать специальную перегрузку, но это только для compile time).

И если посмотреть в доки (https://en.cppreference.com/w/cpp/string/basic_string/basic_string), то видно, что в 23 стандарте благодать снизошла и добавили такое

constexpr basic_string( std::nullptr_t ) = delete;

Но изначально разработчики стандарта приняли странное решение — на nullptr в конструкторе не проверять явно и никак не обрабатывать такой случай специально (да, странное решение).

там же в доках описано, что этот конструктор покрывает чуть больше случаев

  1. Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

То есть, длина (и конец) строки определяется по нулевому символу. Если же полученный диапазон некорректный, то и поведение такое же. Случай с nullptr там описан отдельно и как по мне, то похоже это кто то просто не нашел лучше объяснения. (да, наверное тут имелось ввиду, что если нулевой символ будет найден вне приделов выделенной памяти под строку, то диапазон некорректный, но стандарт так сильно старается избегать явного упоминания простых вещей, что иногда заходит так далеко. А вот случай с nullptr, как мне кажется, тут сильно сильно притянут за уши. Видимо просто не смогли договорится, что именно делать в этом случае. Но это мои догадки)

Вот здесь https://groups.google.com/a/isocpp.org/g/std-proposals/c/PGdx39Iy8pg пишут, что это было сделано в целях производительности. Возможно.

Как показывает proposal p2166r1 проблема значительно глубже, чем изначально предполагали.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Xsolla genshin impact произошла ошибка
  • Xliveinitialize lost planet как исправить
  • Xlive dll для gta 4 ошибка
  • Xlive dll для fallout 3 ошибка при запуске
  • Xlive dll для fallout 3 как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии