In visual studio Write a test program in c++ language that prompts the user to e
ID: 3710435 • Letter: I
Question
In visual studio Write a test program in c++ language that prompts the user to enter an expression and displays the split items in reverse order.
1. Use the vector class from the standard template library.
2. Declare a string variable to store the expression input by the user
3. Write function split of type vector that is passed your expression
a. Your function will need a local string variable to “build” your number string
b. Loop through each character in expression.
i. If the character is a digit, append it to your number string
ii. If the character is not a digit and you have a number string with size > 0 store the number string in the vector, and erase the number string
iii. If the character is a space, add the next character (an operator) to the vector
c. After the loop, if the size of the number string is > 0, add it to the vector
Explanation / Answer
Solution:
code:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<string> split(string line){
vector<string> data;
string num ="";
for (int i = 0; i<line.size(); i++){
if (line[i] >= '0' && line[i] <= '9'){
num = num + line[i];
}
else if (line[i] != ' '){
string s = "";
s = s + line[i];
data.push_back(s);
}
else {
if (num.size() > 0){
data.push_back(num);
num = "";
}
}
}
return data;
}
vector<string> splitreverse(string line){
vector<string> data;
string num ="";
for (int i = line.size()-1; i>=0; i--){
if (line[i] >= '0' && line[i] <= '9'){
num = line[i] + num;
}
else if (line[i] != ' '){
string s = "";
s = s + line[i];
data.push_back(s);
}
else {
if (num.size() > 0){
data.push_back(num);
num = "";
}
}
}
if (num.size() > 0)
data.push_back(num);
return data;
}
int main(){
vector<string> data;
string line;
cout << "Enter an expression :";
getline(cin,line);
data = split(line);
for (int i = 0; i<data.size(); i++){
cout << data[i] << ",";
}
cout << endl;
data = splitreverse(line);
for (int i = 0; i<data.size(); i++){
cout << data[i] << ",";
}
return 0;
}
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.