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(str ing text)
{
int integer=0, temp=1;
for (int i=text.size()-1, j=1;i>=0;i--, j++)
{
switch (text[i]) {
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[i]<<endl;
}
int main()
{
ifstream is("D:/dataa.txt");
vector<vector<i nt> > theMat;
string data = "";
char c;
int number;
for (int i=0;;i++)
{
while (is.get(c)) {
if (c == '\t') theMat[i].push_back(stri ngToInt(data));
//here is the problem: the program crashes
else if (c == '\n') break;
else data += c;
}
}
print(theMat[0]);
/*string test = "132435";
cout <<stringToInt(t est); */
system("pause") ;
return 0;
} 3 3226
On 25 Dec 2005 12:20:26 -0800, "Al" <al************ @gmail.com> wrote: 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?
Yes. You want either std::stringstre am or the CRT strtod() function.
The latter is better for sanity-checking of input. The former is
easier to use.
Here's the code:
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std;
int stringToInt(str ing text)
Since you do not change "text", it should be passed by const
reference. Otherwise, you are copying it unnecessarily.
{ int integer=0, temp=1;
It's considered bad style by many people to declare more than one
variable on the same line.
for (int i=text.size()-1, j=1;i>=0;i--, j++)
What happens when text.size() == 0?
What happens when text.size() > 10?
What happens when text holds non-digit characters?
What happens when text is negative?
Where is j used in the loop?
{ switch (text[i]) {
This is not necessarily portable code because you are making
assumptions about the internal representation of the particular
character encoding used. Better to use something like this:
case '1':
integer += temp; break;
case '2':
integer += 2 * temp; break;
// etc.
Note the single quotes used.
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<cla ss T> void print(vector<T> v) { for (int i=0; i<v.size(); i++)
size() returns unsigned. It's a very bad mistake to compare signed
with unsigned values, even if your compiler lets you do it. Turn up
your warning level so that you at least get a warning about it here.
cout << i <<" : "<<v[i]<<endl; }
int main() { ifstream is("D:/dataa.txt"); vector<vector<i nt> > theMat; string data = ""; char c; int number; for (int i=0;;i++) { while (is.get(c)) {
The std::getline() function is much better than reading a file
character-for-character.
if (c == '\t') theMat[i].push_back(stri ngToInt(data)); //here is the problem: the program crashes
theMat is a vector of vectors. It was never initialized. Therefore, it
has no elements, yet you use element 0, therefore it crashes.
else if (c == '\n') break; else data += c; } } print(theMat[0]); /*string test = "132435"; cout <<stringToInt(t est); */
system("pause") ; return 0; }
--
Bob Hairgrove No**********@Ho me.com
Al wrote in message
<11************ **********@o13g 2000cwo.googleg roups.com>... What is the problem with this code? It always crashes at the 'push_back'. I found that thanks to debugging. Any Ideas?
// You need to initialize the vector with a size:
// here's one way:
size_t rows(480);
size_t cols(640);
vector<vector<i nt> > theMat( rows, cols);
size_t row(4);
size_t col(6);
theMat.at(row). at(col) = 43; // set 5th row, 7th col to 43
// unless you are positive the index[s] are not out-of-range
// you should use the at() to access the vector[s].
// another way to do it
vector<vector<i nt> > theMat;
for(size_t i(0); /* you need a way out */ ; ++i){
std::vector<int > tmp;
theMat.push_bac k( tmp ); // each pass add another row.
while (is.get(c)) {
if (c == '\t') theMat.at( i ).push_back( FromString<int> (data) );
// ...... fill in data ....
} //while()
if( not is ) break;
} // for()
Other question: what is a faster way to convert a string to an integer? Is there a built-in function to do that?
There are stringstream ToString() and FromString() templates/methods in some
FAQs.
#include <sstream>
// --- string to any number ---
template<typena me T> T FromString(std: :string const &str){
std::istringstr eam is(str); T tmp; is >> tmp; return tmp;
} //FromString()
// -- use it like this --
std::string Str("54321");
int num = FromString<int> (Str);
double num2 = FromString<doub le>(Str);
Heed Mr. Hairgrove's suggestions.
The comp.lang.c++ FAQ is available at http://www.parashift.com/c++-faq-lite/
[corrections always welcome]
--
Bob R
POVrookie
"BobR" <Re***********@ worldnet.att.ne t> wrote in message
news:Uk******** *************@b gtnsc04-news.ops.worldn et.att.net... Other question: what is a faster way to convert a string to an integer? Is there a built-in function to do that?
There are stringstream ToString() and FromString() templates/methods in some FAQs.
#include <sstream> // --- string to any number --- template<typena me T> T FromString(std: :string const &str){ std::istringstr eam is(str); T tmp; is >> tmp; return tmp; } //FromString() // -- use it like this -- std::string Str("54321"); int num = FromString<int> (Str); double num2 = FromString<doub le>(Str);
Here is the version I use:
#include <sstream>
template<typena me T, typename F > T StrmConvert( F from )
{
std::stringstre am temp;
temp << from;
T to = T();
temp >> to;
return to;
}
The advantage of this version is that you can convert from/to std::string
without problems using your same syntax.
int num = 12345;
std::string str("67890");
std::string str2 = StrmConvert<std ::string>( num );
int num2 = StrmConvert<int >( str );
You don't have to specify the type to convert from, the template figures
that out itself (somehow I'm not really positive on the mechanics). You
just have to specify what you are converting to. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: David Jones |
last post by:
Hi
I have a list of values stored in a vector e.g.
std::vector<int> x;
x = 1;
x = 4;
x = 2;
x = 4;
|
by: Tran Tuan Anh |
last post by:
Dear all,
I am new in C++, and now get confused about a lot of things.
I wrote this simple code to test the vector.
class Temp { public: int x; };
int main() {
vector<Temp> v;
|
by: Dave |
last post by:
I'm crossposting this to both comp.lang.c++ and gnu.gcc because I'm not
sure if this is correct behavior or not, and I'm using the gcc STL and
compiler.
When calling vector<int>::push_back(0), an iterator that I've set in a
loop gets changed. Here's an example of the problem (sorry about the
lack of indentation, posting this from Google):
#include <vector>
#include <iostream>
|
by: Venn Syii |
last post by:
I've searched all the forums but cannot find an answer to this question.
I do the following:
vector<MyClass*> myClassList;
Later in the program I try to add to myClassList with a .push_back(...)
I get an "out of memory" runtime error. I know I'm not out of memory
because normal vectors such as vector<int> a, still work, and still work
fine.
|
by: Billy Patton |
last post by:
I have a polygon loaded into a vector. I need to remove redundant points.
Here is an example line segment that shows redundant points
a---------b--------c--------d
Both b and c are not necessary. The function below is supposed to remove this
It seems to work unitl the last point is removed. It seems to have something
to do with the fact that vp->end() is a redundant point. THe test case is code
so that "a" is the initial point,...
| |
by: Lorn |
last post by:
Hopefully someone can help me out with this problem I'm having with 2d
vectors. My vector initialization looks like this:
struct Object {
double d1;
double d2;
int i1;
};
std::vector<std::vector <Object> > vMain;
|
by: Jia |
last post by:
Hi all,
I have a class foo which has a static vector of pointers of type base
class, and a static function to set this vector.
#include <iostream>
#include <vector>
using namespace std;
class super{
protected:
|
by: Josefo |
last post by:
Hello, is someone so kind to tell me why I am getting the following
errors ?
vector_static_function.c:20: error: expected constructor, destructor,
or type conversion before '.' token
vector_static_function.c:21: error: expected constructor, destructor,
or type conversion before '.' token
|
by: Bryan |
last post by:
Hello all. I'm fairly new to c++. I've written several programs
using std::vectors, and they've always worked just fine. Until today.
The following is a snippet of my code (sorry, can't include all of it-
it's over 1k lines long). In addition, I'm including an "include"
file where structures like "stack" are defined. Again, it's really
long. I doubt the problem lies there, though, because the include
file is used in many other...
|
by: Ramon F Herrera |
last post by:
Newbie alert: I come from C programming, so I still have that frame of
mind, but I am trying to "Think in C++". In C this problem would be
solved using unions.
Hello:
Please consider the snippet below. I have some objects which are
derived (subclassed?, subtyped?) from simpler ones, in increasing
size. There is a linear hierarchy. I need to keep them all in some
sort of linked list (perhaps std::vector). I could have several
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |