Very basic help with string library related task

Hey guys, I have got a task for my programming class to make a program that would read a word like "2AXZ5Y" and write "AAXZYYYYY" and I can't get it to work. Can someone please help me? (also tell me if you know how to make it simpler)

P.S. In the mentioned example my program would return 2aaaaaaa...

EDIT: Used "isdigit" now, but it still couts the character after a number forever.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main () {
    string w, n;
    int i, j, x;
    cin>>w;
    for (i=0; i<w.length(); i++) {
        if (isdigit(w[i])) {
            x=w[i];
            for (j=1; j<x; j++) n+=w[i+1];
        }
        else n+=w[i];
    }
    cout<<n;
    return 0;
}
}
Last edited on
Treat numbers differently from letters.

Read a character. If it's a number (std::isdigit), then read the next character and print it however many times that number says. Otherwise, just print the character as-is.
The error is in line 11 ...

Suppose w[i] == '2'
It is completely different from 2

It will assign to x the Ascii order of 2 which is 50
and not 2 ...

Last edited on
After you fix that, you may want to think about what would happen if you input "12A".
We only have to do it for integers from 2 to 9 for now.
Topic archived. No new replies allowed.