Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am trying to convert a string to an integer in C++ and, when I try to compile,

ID: 3534676 • Letter: I

Question

I am trying to convert a string to an integer in C++ and, when I try to compile, I get the following errors:


project.cpp: In function âvoid read_file(String, Vector<Chrono::Appointment>&)â:
project.cpp:44:21: error: cannot convert âStringâ to âintâ in assignment
project.cpp:47:21: error: cannot convert âStringâ to âintâ in assignment
project.cpp:50:21: error: cannot convert âStringâ to âintâ in assignment


The following code is lines 39 to 52 of the read_file function:

if ( !isalpha( linev[i][0] ) )
{
stoi( linev[i] ) ;
switch (i) { //Decides which part of the date to assign linev[i] to
case 0:
dat.m = linev[i] ; //This is line 44
break ;
case 1:
dat.d = linev[i] ;
break ;
case 2: //Will not always have a year value
dat.y = linev[i] ;
break ;
}

}

Explanation / Answer

String to Integer conversion can be done in many ways.

It is not very difficult to do that


I ll tell you how to do that.


Mehod 1


std::string myString = "45";

int value = atoi(myString.c_str()); //value = 45



Method 2


ifastream<basic_formatters, string_reader> myString(&string);

int value;

myString >> value;

Method 3


#include <sstream>

#include <string>

using namespace std;


string myStream = "45";

istringstream buffer(myString);

int value;

buffer >> value; // value = 45


Method 4


The stringstream way can be also used without having a named object:




string str = "123";

int numb;

istringstream ( str ) >> numb;



Method 5


#include <boost/lexical_cast.hpp>


try {

int x = boost::lexical_cast<int>( "123" );

} catch( boost::bad_lexical_cast const& ) {

std::cout << "Error: input string was not valid" << std::endl;

}



Up to you which one, you want to follow.. All of them work..



You can exchange your conversion method with any of these. They are just llike 2-3 lines. Will take your 60 seconds to do that.


Dont forget to rate.


Cheers!!!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote