How can I convert the strings to integers?
Hello, everybody can y'all be so kind to help me with my program? I am trying to convert strings to integers. This is my task:
Open a file "numbers.txt"
read integer numbers as strings from the file (one number per line)
convert each string to a numeric representation (without using stoi() or similar functions from the string library)
store converted numbers in an array
close "numbers.txt"
So far I have read integer numbers as strings but cannot convert the string array to integers without using the string library. Can someone help? My code won't compile but I am trying to do this: 154: Sum = 4*1 + 5*10 + 1*100 = 154 so it can convert to an integer.
This is what I have so far:
Code:
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int StringToInteger( string arraySize);
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int size = 1000;
string myArray[size];
int i = 0;
while (infile >> myArray[i])
{
cout << "The string is \"" << myArray[i] << "\"" << endl;
myArray[i].size();
cout << i << endl;
StringToInteger(i);
++i;
}
}
int StringToInteger( string arraySize)
{
int values = 0;
for (int index = 0; index < arraySize.size; index++) {
values *= 10;
values += (arraySize[index] - '0');
}
return values;
}
Re: How can I convert the strings to integers?
Code:
StringToInteger(i);
StringToInteger() requires a type string as a parameter and you are passing i which is of type int.
Code:
for (int index = 0; index < arraySize.size; index++) {
.size is a function and so should be
Code:
for (int index = 0; index < arraySize.size(); index++) {
If you are required to store the converted numbers in an array, why are you defining myArray as being of type string? Shouldn't this be of type int? Also why are reading the string from the file into myArray? Why not just read it into a string variable, then convert it and store it into the required array?
Also you are not checking that the file has been opened OK. Also what happens if there are more lines in the file then the specified size of the array?