Question:
C++ Code conver strings to int?
Elie
2011-11-05 06:27:19 UTC
Hey i have a code that i wrote and it wont covert... a person said "You either need to make your ids strings, or convert your searchforID into an integer."

because line 36 is causing a problem.. i worked for hours on it and on my 2nd Tylenol...

Could somehow please edit the code so i compare the original to the new cause this is really driving me nuts...

line 36 : while (x < 5 && ids[x] != searchforID)


//Ch11AppE12.cpp
//Displays the price and quantity corresponding
//to the item ID entered by the user
//Created/revised by Greg Schader on 7/13/2009

#include
#include
#include

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::transform;

int main()
{
//declare arrays
string searchforID = "";
int ids[5] = {10, 14, 34, 45, 78};
int prices[5] = {125, 600, 250, 350, 225};
int quantities[5] = {5, 3, 9, 10, 2};

//Enter product ID
cout << "Enter product ID (X to exit): ";
getline(cin, searchforID);
transform (searchforID.begin(), searchforID.end(),
searchforID.begin(), toupper);



while (searchforID != "X")
{
//Find product ID
int x = 0;
while (x < 5 && ids[x] != searchforID)
x = x + 1;

//If product ID is valid, display price and quantity
// otherwise, display error message
if (x<5)
cout << "Price for product ID " << ids[x] << ": $" << prices[x] << " and quantity is: " << quantities[x] << endl << endl;
else
cout << "Invalid product ID" << endl << endl;
//end if function

//Enter product ID
cout << "Enter product ID (X to exit): ";
getline(cin, searchforID);
transform (searchforID.begin(), searchforID.end(),
searchforID.begin(), toupper);
} //End of while function




return 0;
} //end of main function
Three answers:
Shingetsu Kurai
2011-11-05 06:44:21 UTC
actually there's a simple utility to convert a string to an int:

atoi.

it's located in #include



it's used like so:



string temp = "1234";

int output;

output = atoi(temp);
?
2011-11-05 08:14:50 UTC
You can use the atoi function from the C library

convert your C++ string to a c string with the member function c_str()





#include

#include

#include

int main(void){



string s="23";



cout << atoi(s.c_str());

return 0;

}
severino
2016-12-10 16:48:00 UTC
hi! right here is the output of the 1st code snippet: ">>>123" I dont understand java plenty yet right here is the code for 2d question in c++. you could convert it into java. i think of a great variety of the code is already valid in java. #comprise int significant() { char letters[26]; //a million extra for the null terminator for (int i=sixty 5,j=0;i<=ninety;i++,j++) { letters[j]=(char)i; } for (int ok=0;ok<26;ok++) { cout << letters[ok]; if (ok!=25) { cout<<", "; } } } //cout in c++= device.out.printIn() in simple terms upload the tester classification to that code as you like in java. wish this helps. :-)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...