homework help: multiplying a string in c++

Hi guys, I am new to c++,
I have a homework and I have no idea how to do it. I need a program that get a character and a number between <>, word and a number between [] or a sentence between () and multiply it. Example:

Input: A<4>
Output: A A A A

Input: good[3]
Output: good good good

Input: A is good. (2)
Output: A is good. A is good.

Thanks for your help.
Last edited on
Get the <string>.
Get the <number>.
Use a for loop that outputs the string; loop how many times? The <number> times.
The user should enter the string and number in a sentence like: it is a sentence(2)
and the program should print: it is a sentence. it is a sentence.
@Moschops
One way to do this is:

declare a variable string line and get the input from the console.

Use string.find_first_of("(<[") to separate the text from the rest.

Remove <([])> from the rest - this gives you the number.

Print the text number of times.
i think it's more suitable to use string.find_last_of("(<["), because we may input these characters in the front part.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<string>
#include<iostream>

using std::cin;
using std::cout;
using std::string;

int main()
{
    cout<<"Input : ";
    string s;
    getline(cin,s);
    auto p1 = s.find_last_of("(<[");
    auto p2 = s.find_last_of(")>]");
    auto s1 = s.substr(0,p1);
    int times = stoi(s.substr(p1+1,p2));
    cout<<"Output: ";
    while(times--)
        std::cout<<s1<<" ";
}
Last edited on
@qishuhao
thanks for your code, but I get error on dev c++, siad: p1 does not name a type. and p1 was not declared in this scope.
It seems your dev c++ does not understand C++11.
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <iostream>

using std::cin;
using std::cout;
using std::string;

int main()
{
  cout<<"Input : ";
  string s;
  getline(cin,s);
  string::size_type p1 = s.find_last_of("(<[");
  string::size_type p2 = s.find_last_of(")>]");
  string s1 = s.substr(0,p1);
  int times = stoi(s.substr(p1+1,p2));
  cout<<"Output: ";
  while(times--)
    std::cout << s1 << " ";

  system("pause");
}
@Thomas1965
again error: stoi and system was not declared in this scope.
error "system ... " fixed with #include <cstdlib> but stoi still has problem.
As Thomas1965 said, you're not using a C++11 compiler, or have not turned on the C++11 option if your compiler supports that. stoi is only available in C++11.

If enabling C++11 is not an option, you can alternatively use stringstream.

1
2
3
4
5
#include <sstream>
... // Replace line 16 with the following:
  stringstream ss ((s.substr(p1+1,p2));
  int times;
  ss >> times;

Last edited on
Topic archived. No new replies allowed.