C ++ converts int to string?

advertisements

This question already has an answer here:

  • How to convert a number to string and vice versa in C++ 3 answers

I tried to convert int into a string , but it doesn't work I dont know why... here my Code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <array>

using namespace std;

int main()
{
    struct Studentendaten {
        int matrnr;
        string name;
        string vorname;
        string datum;
        float note;
    };
    Studentendaten stud;
    array<Studentendaten,100> studArray ;   

  FILE * pFile;
  int ch;
  int mnr;
  string sub;
  string sub1;
  string sub2;
  string sub3;
  string sub4;
  string sub5;

  int i = 0;
  int pos ;

  pFile=fopen("studentendaten.txt","r");
  if (pFile==nullptr)
  {
      perror ("Fehler beim öffnen der Datei");
  }
  else
  {
    while (ch != EOF)
    {
      ch = fgetc(pFile);
      sub += (char)(ch);
      pos = sub.find(";");
      if (pos != -1)
      {
          sub1 = sub.substr(0,pos);
          sub2  = sub.substr(pos+1,pos);
          sub3  = sub.substr(pos+1,pos);
          sub4  =sub.substr(pos+1,pos);
          sub5  =sub.substr(pos+1,pos);
          mnr   =stoi(sub1);
          stud.matrnr = mnr;
          stud.name = sub2;
          stud.vorname = sub3;
          stud.datum = sub4
          stud.note = float(sub5);
      }
      if (ch == '\n')
      {
          stud = {matrn,name,vorname,datum,note};
          studArray.[i] = stud;
          i++;
      }

      putchar(ch);
    }
    fclose (pFile);
    }

  return 0;
}

I tried int mnr =stoi(sub1); as well as int mnr = atoi(sub1); where sub1 = "029383214" something like that.... why does it not work? Compiler complains...


Simply use a std::stringstream:

int parse_int( const std::string& str )
{
    std::stringstream ss( str );
    int value;

    if( ss >> value )
        return value;
    else
        throw;
}