A
Al
What is the problem with this code? It always crashes at the
'push_back'. I found that thanks to debugging. Any Ideas?
Other question: what is a faster way to convert a string to an integer?
Is there a built-in function to do that?
Here's the code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int stringToInt(string text)
{
int integer=0, temp=1;
for (int i=text.size()-1, j=1;i>=0;i--, j++)
{
switch (text) {
case 49:
integer += temp; break;
case 50:
integer += 2 * temp; break;
case 51:
integer += 3 * temp; break;
case 52:
integer += 4 * temp; break;
case 53:
integer += 5 * temp; break;
case 54:
integer += 6 * temp; break;
case 55:
integer += 7 * temp; break;
case 56:
integer += 8 * temp; break;
case 57:
integer += 9 * temp; break;
default: break;
}
temp *= 10;
}
return integer;
}
template<class T>
void print(vector<T> v)
{
for (int i=0; i<v.size(); i++)
cout << i <<" : "<<v<<endl;
}
int main()
{
ifstream is("D:/dataa.txt");
vector<vector<int> > theMat;
string data = "";
char c;
int number;
for (int i=0;;i++)
{
while (is.get(c)) {
if (c == '\t') theMat.push_back(stringToInt(data));
//here is the problem: the program crashes
else if (c == '\n') break;
else data += c;
}
}
print(theMat[0]);
/*string test = "132435";
cout <<stringToInt(test); */
system("pause");
return 0;
}
'push_back'. I found that thanks to debugging. Any Ideas?
Other question: what is a faster way to convert a string to an integer?
Is there a built-in function to do that?
Here's the code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int stringToInt(string text)
{
int integer=0, temp=1;
for (int i=text.size()-1, j=1;i>=0;i--, j++)
{
switch (text) {
case 49:
integer += temp; break;
case 50:
integer += 2 * temp; break;
case 51:
integer += 3 * temp; break;
case 52:
integer += 4 * temp; break;
case 53:
integer += 5 * temp; break;
case 54:
integer += 6 * temp; break;
case 55:
integer += 7 * temp; break;
case 56:
integer += 8 * temp; break;
case 57:
integer += 9 * temp; break;
default: break;
}
temp *= 10;
}
return integer;
}
template<class T>
void print(vector<T> v)
{
for (int i=0; i<v.size(); i++)
cout << i <<" : "<<v<<endl;
}
int main()
{
ifstream is("D:/dataa.txt");
vector<vector<int> > theMat;
string data = "";
char c;
int number;
for (int i=0;;i++)
{
while (is.get(c)) {
if (c == '\t') theMat.push_back(stringToInt(data));
//here is the problem: the program crashes
else if (c == '\n') break;
else data += c;
}
}
print(theMat[0]);
/*string test = "132435";
cout <<stringToInt(test); */
system("pause");
return 0;
}