473,769 Members | 6,838 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

string --> int[]

Hello NG!

Though I´m not new to programming at all, i´m new to C++.

got the following question/problem with it´s behaviour:

- read number with *arbitrary number of digits* from keyboard (done)
- then calculate average value and variety of digits

the second sould be no problem, too, i think.

the problem is as follows:

how can i create a int[] from my read string with each element
representing *one* digit from string?

i tried this:
----------------------------------------
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <String.h>

using namespace std;

int main(int argc, char *argv[])
{

string a;

cout << "Beliebige Ziffernfolge eingeben" << endl;
cin >> a;

int b[sizeof(a)-1];

for (byte i = 0; i < sizeof(a)-1; i++) {
b[i] = atoi(&a[i]);
}

for (byte i = 0; i < sizeof(a)-1; i++) {
cout << b[i] << endl;
}

cout << endl;
system("PAUSE") ;
return 0;
}
----------------------------------------

doesn´t work! for a="123" i get:
b[0] = 123
b[1] = 23
b[2] = 3

instead of (what i would need):
b[0] = 1
b[1] = 2
b[2] = 3
what´s my failure?

greetings,
Frank
Jul 19 '05 #1
13 2553
On Wed, 15 Oct 2003 23:03:13 +0200, Frank Wagner
<ne************ *****@nofusion. de> wrote:
Hello NG!

Though I´m not new to programming at all, i´m new to C++.

got the following question/problem with it´s behaviour:

- read number with *arbitrary number of digits* from keyboard (done)
- then calculate average value and variety of digits

the second sould be no problem, too, i think.

the problem is as follows:

how can i create a int[] from my read string with each element
representing *one* digit from string?

i tried this:
----------------------------------------
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <String.h>

using namespace std;

int main(int argc, char *argv[])
{

string a;

cout << "Beliebige Ziffernfolge eingeben" << endl;
cin >> a;

int b[sizeof(a)-1];

for (byte i = 0; i < sizeof(a)-1; i++) {
b[i] = atoi(&a[i]);
}

for (byte i = 0; i < sizeof(a)-1; i++) {
cout << b[i] << endl;
}

cout << endl;
system("PAUSE") ;
return 0;
}
----------------------------------------

doesn´t work! for a="123" i get:
b[0] = 123
b[1] = 23
b[2] = 3

instead of (what i would need):
b[0] = 1
b[1] = 2
b[2] = 3
what´s my failure?
atoi takes const char* and ends conversion when it encounters non digit
character,

To convert char to integer - you should just use expression digit -'0'
b[i] = a[i]-'0';
instead of atoi in the loop above.


greetings,
Frank


--
grzegorz
Jul 19 '05 #2
Frank Wagner wrote:
Hello NG!

Though I´m not new to programming at all, i´m new to C++.

got the following question/problem with it´s behaviour:

- read number with *arbitrary number of digits* from keyboard (done)
- then calculate average value and variety of digits

the second sould be no problem, too, i think.

the problem is as follows:

how can i create a int[] from my read string with each element
representing *one* digit from string?

i tried this:
----------------------------------------
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <String.h>

using namespace std;

int main(int argc, char *argv[])
{

string a;

cout << "Beliebige Ziffernfolge eingeben" << endl;
cin >> a;

int b[sizeof(a)-1];

for (byte i = 0; i < sizeof(a)-1; i++) {
b[i] = atoi(&a[i]);

Your failure is here.

Assuming that a std::string keeps its characters in a byte array (which
I don't know - experts?)...Wha t you are doing is passing atoi your
entire string minus the first 'i' characters. Therefor your first
iteration passes "123", your second "23", your third "3"...and you get
the results you are seing.

You could:

a) Assume that you are working with ASCII and "b[i] = a[i] - '0'". This
will break on systems that use a character set where 0-9 is not concurrent.
b) create a char[2] array and fill with a[i], '\0' and pass this to
atoi....this will always work.

NR

Jul 19 '05 #3
On Wed, 15 Oct 2003 23:03:13 +0200, Frank Wagner <ne************ *****@nofusion. de> wrote:
Hello NG!

Though I´m not new to programming at all, i´m new to C++.

got the following question/problem with it´s behaviour:

- read number with *arbitrary number of digits* from keyboard (done)
Concentrate on the digits, which is a string of characters.

- then calculate average value and variety of digits
Variety?

the second sould be no problem, too, i think.

the problem is as follows:

how can i create a int[] from my read string with each element
representing *one* digit from string?

std::vector<int > v;
for( std::size_t i = 0; i < s.size(); ++i )
{
v.push_back( s[i] - '\0' );
}

i tried this:
----------------------------------------
#include <iostream>
#include <stdlib.h>
Use
#include <cstdlib>
#include <math.h>
Use
#include <cmath>

#include <String.h>
<string.h> is not the same header as <string>


using namespace std;

int main(int argc, char *argv[])
{

string a;
You're unlucky if this compiles (it might, depending on what <vector> drags
in).

cout << "Beliebige Ziffernfolge eingeben" << endl;
cin >> a;

int b[sizeof(a)-1];
You need a.size(), not sizeof(a). The former tells you the number of characters
stored in the string, the latter the size in bytes of the container variable
(which typically holds just a pointer to the character buffer, plus a few other
values such as the current length returned by the size() member function).


for (byte i = 0; i < sizeof(a)-1; i++) {
There's no predefined data type 'byte' in standard C++.

Also, use '++i', not 'i++'.
b[i] = atoi(&a[i]);
'atoi' expects a zero-terminated string of digits, which you're giving
it, namely a[i] and all following characters until the terminating zero...
}

for (byte i = 0; i < sizeof(a)-1; i++) {
See above.

cout << b[i] << endl;
}

cout << endl;
system("PAUSE") ;
This will only work on a system with a "PAUSE" command (e.g. Windows), and
it will make it slightly more difficult to test the program automatically, or
to use it in automation.

return 0; ¨
OK, but you don't need it (a special feature of 'main' is that it returns 0
by default).
}
----------------------------------------

doesn´t work! for a="123" i get:
b[0] = 123
b[1] = 23
b[2] = 3

instead of (what i would need):
b[0] = 1
b[1] = 2
b[2] = 3
what´s my failure?


That, I don't know... ;-)

Jul 19 '05 #4
Alf P. Steinbach wrote:
for (byte i = 0; i < sizeof(a)-1; i++) {


Also, use '++i', not 'i++'.


Why?

--
Unforgiven

A: Top Posting!
Q: What is the most annoying thing on Usenet?
Jul 19 '05 #5
On Thu, 16 Oct 2003 00:22:59 +0200, "Unforgiven " <ja*******@hotm ail.com> wrote:
Alf P. Steinbach wrote:
for (byte i = 0; i < sizeof(a)-1; i++) {


Also, use '++i', not 'i++'.


Why?


Several reasons, all having to do with good coding practice.

The most important reason is that "++i" works with most kind of data types
providing an increment operation, whereas "i++" does not. In particular
for iterators. So getting used to writing "++i" as default is a good idea.

The most often encountered reason is that "++i" has a less error-prone
side-effect than "i++", in other words, is a tad less unsafe.

The most religious reason is that with "i++" extra work is requested, which
is only meaningful if that work is contributing towards the code's overall
purpose; and meaningless code should be avoided.

The most easily grasped reason, for complete novices (if you have some
experience this can be very difficult to grasp since it's only technically
true, not usually relevant to anything), is that "++i" can be more efficient
than "i++", e.g. see the FAQ §13.12.

Jul 19 '05 #6
Thank you for your help! Did it, but now got another problem:

if i have:
int b[3];

it´s:
sizeof(b) = 12; // cause sizeof(int) = 4

but if i do sth like this:
-----------------------------------
void my_function(int arr[])
{
....
sizeof(arr);
// sizeof(arr) only returns 4!!! what´s happened?
....
}

void main()
{
....
int b[3];
// sizeof(b) returns 12 - so everythings alright...
my_function(b);
....
}
-----------------------------------

there´s inside of my_function:
sizeof(arr) = 4;

What´s happening here, and how can i receive the "correct" value for
sizeof(b) in my functions? ("correct" now means 12 to me ;) )

thanks for your time!

greetings,
Frank

Jul 19 '05 #7
On Wed, 15 Oct 2003 21:35:00 GMT, al***@start.no (Alf P. Steinbach) wrote:
std::vector<int > v;
for( std::size_t i = 0; i < s.size(); ++i )
{
v.push_back( s[i] - '\0' );
}


Oops, keyboard error: that should be '0' not '\0'.

Jul 19 '05 #8
You could also use stringstreams instead of atoi to convert your string
into an int, something like this

template<typena me RT, typename T, typename Trait, typename Alloc>
RT ss_atoi( std::basic_stri ng<T, Trait, Alloc>& the_string )
{
std::basic_istr ingstream< T, Trait, Alloc> temp_ss(the_str ing);
RT num;
temp_ss >> num;
return num;
}

Or use boost::lexical_ cast
Jul 19 '05 #9
Frank Wagner wrote:
Thank you for your help! Did it, but now got another problem:

if i have:
int b[3];

it´s:
sizeof(b) = 12; // cause sizeof(int) = 4

but if i do sth like this:
-----------------------------------
void my_function(int arr[])
{
...
sizeof(arr);
// sizeof(arr) only returns 4!!! what´s happened?
...
}

void main()
{
...
int b[3];
// sizeof(b) returns 12 - so everythings alright...
my_function(b);
...
}
-----------------------------------

there´s inside of my_function:
sizeof(arr) = 4;

What´s happening here, and how can i receive the "correct" value for
sizeof(b) in my functions? ("correct" now means 12 to me ;) )


This is always a bit tricky. You have to remember that when you pass an
array into a function, you are actually passing a pointer to the array.
Therefor when you try and get its size, you end up with the size of the
pointer.

The way around it is to pass the length of the array in as a second
parameter, or even easier, pass it in as a std::vector<int >&.

<code>

#include <vector>

void my_function(std ::vector<int>& arr)
{
arr.size(); // 3
}

int main()
{
std::vector<int > b(3);
b.size() // 3

my_function(b);
}

</code>

Ryan

Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1578
by: Madhusudan Singh | last post by:
Hi I am working with an application that I designed with the Designer > pyuic workflow and I get the following error on trying to process the contents of a combobox : Traceback (most recent call last): File "measure.py", line 908, in acquiredata np=self.getNPrange()
12
2761
by: grubbymaster | last post by:
hello i'm extracting from a file numbers that are stored on each line. this is the only way i know to extract each line at a time from a file , using <fstream> <ostream> : char buffer; ifstream LZW(sz_path);
8
1800
by: Aske | last post by:
Hi, I'm having a problem for casting a string to int, so tht evry number in the string becomes a diff int. Cus I get wrong numbers back. I'll post an example its sumtin like this: int main(void){ int x_rij, x_kolom, y_rij, y_kolom; char spel_request; scanf("%s",&spel_request);
0
9423
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,...
0
10050
jinu1996
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...
1
9999
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
agi2029
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...
1
7413
isladogs
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...
0
6675
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();...
0
5310
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...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.