0

I want to create a string array and then after writing lines into it I want to change one exact character into int. I already know that all the characters are going to be numbers. As my goal is to change the one character at a time, options like atoi, stoi etc. are perhaps off? The closest I got is that:

#include <iostream>
int main() 
{

    int n=0,suma=0,i=0;
    int multiplier[11]={1,3,7,9,1,3,7,9,1,3,1};

    std::cin>>n;

    std::string str[n];

    for (int i = 0; i < n; ++i) 
    {
        std::cin>>str[i];
    }
    for (int i = 0; i < n; ++i) 
    {
        for (int j = 0; j < 11; ++j) 
        {
            i = str[i][j] - '0';
            std::cout << i;
        }
    }
}

Although this is the output I get "1-48"

I know that the string is going to be 11 characters long. Any ideas?

EDIT: It was a single typo that caused my confuse :p Yet still I'm looking forward to read and learn from your suggestions such as using different way to read n (from user input) strings. :)

  • 1
    This is my BOOMSTICK: `std::string str[n];`! Be careful with variable length arrays. They are one-stop shopping for all the user's Stack Overflow needs. Shop smart. Shop S-Mart. – user4581301 Nov 04 '20 at 18:25
  • The declaration `std::string str[n];` is probably wrong. When declaring an array in C++, the value in the brackets *has* to be a constant (which `n` is not). If your compiler lets you get away with what you are doing, then it's not standards-conforming. See here: https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – jjramsey Nov 04 '20 at 18:25
  • 1
    On a more immediately useful note, what is the input you're providing and how are we supposed to interpret "1-48"? Is that a printed output? – user4581301 Nov 04 '20 at 18:28
  • Also, what is the input that gets you "1-48"? And what is `multiplier` supposed to do? – jjramsey Nov 04 '20 at 18:28
  • Thanks for replying. The reply below was the solution for my problem. Although what do you suggest to do in situation like that, when i need to create n strings and then get from each a number? If not my guess what i understand really good, I just don't know the other way to do that. btw. it's a SPOJ task –  Nov 04 '20 at 19:29
  • Also multiplites the same as 'suma' is needed for futher implementation –  Nov 04 '20 at 19:30

1 Answers1

0

In your loop:

for (int i = 0; i < n; ++i) 
{
    for (int j = 0; j < 11; ++j) 
    {
        i = str[i][j] - '0';
        std::cout << i;
    }
}

you are modifying outer loop variable i (looks like for the purpose of printing a value).

Given an unfortunate input, you would go out-of-bounds fast.

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27