Converting string to integer using atoi in C++

  • Context: C/C++ 
  • Thread starter Thread starter zarentina
  • Start date Start date
  • Tags Tags
    C++ Integer String
Click For Summary

Discussion Overview

The discussion revolves around a C++ programming problem involving string manipulation, specifically reversing a string, converting it to an integer using the atoi function, and calculating its square root. Participants explore coding issues, potential improvements, and best practices in C++ programming.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant describes their initial code and expresses confusion about why their reversed string does not convert to an integer correctly, seeking advice on storing the reversed string.
  • Another participant notes that the use of a fixed length (50 characters) for string reversal is problematic and questions the necessity of iterating 50 times regardless of the actual string length.
  • A different participant points out that the character being accessed in the new string is not a complete string, suggesting that the method of counting characters could be simplified.
  • One participant shares their own experience with a similar issue, mentioning random characters appearing in their output and asking for suggestions to correct their approach.
  • Hints are provided regarding the initialization of variables, specifically the variable L, which is crucial for the program's functionality.
  • A participant shares an updated version of the code, indicating that they have made changes based on feedback, and invites further critique or suggestions for improvement.
  • Another participant welcomes the original poster and confirms that their updated code will work, while also suggesting a shift from using char arrays to std::string for better programming style and safety.

Areas of Agreement / Disagreement

Participants generally agree on the need for improvements in the original code and the importance of proper initialization and handling of strings. However, there is no consensus on the best approach to take, as different coding styles and methods are proposed.

Contextual Notes

Limitations include the initial assumption of a fixed string length, which may lead to issues with input truncation and undefined behavior. The discussion also highlights the need for proper variable initialization and the potential pitfalls of using char arrays in C++.

Who May Find This Useful

Readers interested in C++ programming, string manipulation, and best practices in coding may find this discussion beneficial.

zarentina
Messages
12
Reaction score
0
Hello, the problem that I was asked to complete was ; Write a program that inputs a string and reverses it. After the string has been reversed you must convert it to an integer and then take the square root of the integer. (using atoi)
My code is as follows:
Code:
int main ()
{
    int i=0,L=50, S,x,;
    double z;
    char ori_string[50];
    char new_string[50];
    cout<<"Please enter a long string"<<endl;
    cin.getline(ori_string,50);
    
    for(i=0;i<L; i++)
    {
                 new_string[i]=ori_string[L-1-i];
    }
    for(L=50-strlen(ori_string);L<50;L++)
    {
                                        
                                         cout<<new_string[L];
     }
cout<<endl;
{
     x=atoi(new_string);
     z=sqrt(x);
     cout<<"The square root of the reversed string is: "<<z<<endl;
}
    system("pause");
	return 0;
}

My problem is that my program isn't storing "new_string[L]" as anything so when I convert it to a integer nothing is there and the square root is zero. So my question to you all is how can i store "new_string[L]" so I can convert it to an integer using atoi?

Any advice would be delightful!
Thanks,
Z
 
Technology news on Phys.org
I don't know too much about C++ but atoi is string to int and atol is strong to long int.

Your code also seems to have a lot of stuff in it just to reverse a string and find its integer square root.

For example, why would you need anything to do 50 iterations?
 
First of all - you can't reverse the string assuming its length is 50 characters. What happens if it is not?

new_string[L] is a character (element of the new_string array), not a string. You don't have to write new_string to count character by character, count << new_string should work.

There is more, but I am not going to mention anything else now to not muddy the water.
 
When I first wrote this program to reverse my number I simply had
Code:
int main()
{
    int i,L,;
    char ori_string[50];
    char new_string[50];
    cout<<"Please enter a long string"<<endl;
    cin.getline(ori_string,50); 
 
     for(i=0;i<L; i++)
     {
            cout<<ori_string[L-1-i];
     }
         system("pause");
	return 0;
}

This returned the proper number but it was preceded by random characters for the first 46 spaces if the string was 3 digits long. This was the reasoning of structuring a second for loop. Yet now that I know that is the incorrect method, how do you suggest I fix this bit of code here so that it will only output the reverse of the string for after it does that I can easily convert it to an int and take the square root.

(I know this differs from my initial question but I'm reasonably certain that this is where the problem is, yet if this assumption is wrong please let me know!)

Thanks,
Z
 
Hint: L is not initialized.

Hint2: with what should it be initialized?
 
*UPDATE* I had a revelation sparked by a few of your comments:smile:

Code:
int main()
{
    int i,L=50,x;
    double z;
    char ori_string[L];
    char new_string[L];
    cout<<"Please enter a long string"<<endl;
    cin.getline(ori_string,50);
    L=strlen(ori_string); 
 
     for(i=0;i<L; i++)
     {
            
            cout<<ori_string[L-1-i];
            new_string[i]=ori_string[L-1-i];
     }

     {
     x=atol(new_string);
     z=sqrt(x);
     cout<<"The square root of the reversed string is: "<<z<<endl;
}
         system("pause");
	return 0;
}

Is my new properly working code, if there are any critiques or overhauls you may do feel free, I'd love to learn!

Thanks,
Z
 
Hi Z! Welcome to PF! :smile:

You're code will work properly.

If you want to learn I'll give you an improvement.
Your program won't function better, but it is better programming style.

In C++ we don't really want to use char-arrays anymore (it's a remnant from its predecessor C).
There are a number of pitfalls with them.
In this case the most obvious ones are that you have a maximum size (50) and that you truncate your input.

The C++ way to do things, is to use std::string.
It works like this:
Code:
#include <string>

int main()
{
    int i, L, x;
    double z;
    std::string ori_string;
    std::string new_string;
    cout << "Please enter a long string" << endl;
    getline(cin, ori_string);
    
    L = ori_string.length();
    new_string.resize(L);
    for (i = 0; i < L; i++)
    {
        cout << ori_string[L - 1 - i];
        new_string[i] = ori_string[L - 1 - i];
    }

    x = atol(new_string.c_str());
    z = sqrt(x);
    cout << "The square root of the reversed string is: " << z << endl;

    system("pause");
    return 0;
}
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 23 ·
Replies
23
Views
3K
Replies
12
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
10K