So you're to put a value for "a" and a value for "b" and the for loop is to return a string that contains those values and the values between them counting up like so "3456789" when the string is cout. This is probably really simple but Im not getting it to work. I believe I have to use a to_string somewhere in here but I am confused as to how.
#include <iostream>
#include <string>
usingnamespace std;
int main(){
int a, b, c;
int step = 1;
string betweenstring, string;
cout << "Please enter A:\n";
cin >> a;
cout << "Please enter B:\n";
cin >> b;
if (a < b){
for (int i = a; i <= b; i++){
betweenstring[i] = to_string(i);
}
c = b - a;
c += step;
string = betweenstring.subtr(a, c);
}
elseif (a > b){
for (int i = b; i <= a; i++){
betweenstring[i] = to_string(i);
}
c = a - b;
c += step;
string = betweenstring.subtr(b, c);
}
else {
for (int i = a; i <= b; a++){
betweenstring[i] = to_string(i);
}
c = b - a;
c += step;
string = betweenstring.subtr(a, c);
}
cout << string;
return 0;
}
for (int i = a; i <= b; i++){
betweenstring[i] = to_string(i);
}
First problem, is that betweenstring is an empty string right here, so you're accessing characters that don't exist.
Looks overcomplicated, but it looks like you tried, so if you don't mind, I'm just going to re-write it. If you want help with what you already wrote, let us know.
My assumptions are the input is limited from 0-9. This won't work if the input is 11 and 42, or something like that.
// Example program
#include <iostream>
#include <string>
int main()
{
usingnamespace std;
int a, b;
cout << "Please enter A:\n";
cin >> a;
cout << "Please enter B:\n";
cin >> b;
// if a > b, we count down instead
int step = (a > b) ? -1 : 1;
std::string output;
while (a != b)
{
// convert a to a string, append it to the output
output += static_cast<char>(a + '0');
a += step; // iterate to the next number
}
// convert b to a string, add it to the end of the input
output += static_cast<char>(b + '0');
cout << output << '\n';
}
// Example program
#include <iostream>
#include <string>
int main()
{
usingnamespace std;
int a, b;
cout << "Please enter A:\n";
cin >> a;
cout << "Please enter B:\n";
cin >> b;
// if a > b, we count down instead
int step = (a > b) ? -1 : 1;
std::string output;
while (a != b)
{
output += std::to_string(a);
a += step; // iterate to the next number
}
output += std::to_string(b);
cout << output << '\n';
}
#include <iostream>
#include <string>
usingnamespace std;
int main(){
int a, b, c;
int step = 1;
string betweenstring;
cout << "Please enter A:\n";
cin >> a;
cout << "Please enter B:\n";
cin >> b;
if (a < b){
for (int i = a; i <= b; i++)
betweenstring += to_string(i);
}
elseif (a > b){
for (int i = b; i <= a; i++)
betweenstring += to_string(i);
}
else {
for (int i = a; i <= b; i++)
betweenstring += to_string(i);
}
cout << betweenstring;
return 0;
}