Question

Convert Code from Java to C++ Convert : import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class...

Convert Code from Java to C++

Convert :

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Template {
public static void main(String args[]) {
Scanner sc1 = new Scanner(System.in); //Standard input data
String[] line1 = sc1.nextLine().split(","); //getting input and spliting on basis of ","
String[] line2 = sc1.nextLine().split(" "); //getting input and spiliting on basis of " "
  
Map<String, String> mapping = new HashMap<String, String>();
for(int i=0;i<line1.length;i++) {
mapping.put(line1[i].split("=")[0], line1[i].split("=")[1]); //string in map where in [] as key and other as value
}
for(int i=0;i<line2.length;i++) {
if(line2[i].contains("[")) { //check whether it is word or word-template
String temp = line2[i].substring(1,line2[i].length()-1); //removing [] from string and checking the key
line2[i]=mapping.get(temp); //getting the value of defined key from map
}
System.out.print(line2[i]+" "); //printing the array string with spaces.
}
sc1.close(); //closing the input buffer
}
}

Example input
person=Paul,action=strolls around,place=the park
[person] [action] [place]

Example output
Paul strolls around the park

0 0
Add a comment Improve this question Transcribed image text
Answer #1

All the explanation is in the code comments. Hope it helps!

Code:

#include<bits/stdc++.h>
#include <unordered_map>

using namespace std;

// function to split string according to given delimiter
vector <string> split_line(string input,string delim)
{
// resultant array of string
vector <string> result;
size_t prev = 0, pos = 0;
  
// loop till end of string
while (pos < input.length() && prev < input.length())
{
// get the next delimiter index
pos = input.find(delim, prev);
if (pos == string::npos)
{
// for end of index
pos = input.length();
}
// get the substring
string token = input.substr(prev, pos-prev);

// push the result in the array
if (!token.empty()) result.push_back(token);
prev = pos + delim.length();
}
  
// return result
return result;
}

int main(){

string input1,input2;
  
// get input of 2 lines
getline(cin,input1);
getline(cin,input2);
  
// split the strings
vector <string> line1 = split_line(input1,",");
vector <string> line2 = split_line(input2," ");

// corresponding to hashmap in java
unordered_map<string,string> mapping;

for (int i = 0; i < line1.size(); i++)
{
// split the string before and after '='
vector <string> temp = split_line(line1[i],"=");
// put key and value in map
mapping[temp[0]]=temp[1];
}
  
for (int i = 0; i < line2.size(); i++)
{
// get the template type in given position
string temp = line2[i].substr(1,line2[i].size() - 2);
  
// get the template value from map
line2[i] = mapping[temp];
// print it
cout << line2[i] << " ";
}
  
return 0;
}

Sample run:

Code screenshots:

Add a comment
Know the answer?
Add Answer to:
Convert Code from Java to C++ Convert : import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

  • I need the following java code commented import java.util.Scanner; public class Main { public static void...

    I need the following java code commented import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner (System.in); int productNo=0; double product1; double product2; double product3; double product4; double product5; int quantity; double totalsales=0; while(productNo !=0) System.out.println("Enter Product Number 1-5"); productNo=input.nextInt(); System.out.println("Enter Quantity Sold"); quantity=input.nextInt(); switch (productNo) { case 1: product1=1.00; totalsales+=(1.00*quantity); break; case 2: product2=2.00; totalsales+=(2.00*quantity); break; case 3: product3=6.00; totalsales+=(6.00*quantity); break; case 4: product4=23.00; totalsales+=(23.00*quantity); break; case 5: product5=17.00; totalsales+=(17.00*quantity); break;...

  • import java.util.Scanner; public class TempConvert { public static void main(String[] args) { Scanner scnr = new...

    import java.util.Scanner; public class TempConvert { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); //ask the user for a temperature System.out.println("Enter a temperature:"); double temp = scnr.nextDouble(); //ask the user for the scale of the temperature System.out.println("Is that Fahrenheit (F) or Celsius (C)?"); char choice = scnr.next().charAt(0); if(choice == 'F') { //convert to Celsius if given temperature was Fahrenheit System.out.println(temp + " degrees Fahrenheit is " + ((5.0/9) * (temp-32)) + " degrees Celsius"); } else {...

  • Can you help me with this code in Java??? import java.util.Scanner; public class Main { public...

    Can you help me with this code in Java??? import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int rows = 3; int columns = 4; int[][] arr = new int[rows][columns]; for(int i = 0; i < rows; ++i) { for(int j = 0; j < columns; ++j) { System.out.println("Enter a value: "); arr[i][j] = scan.nextInt(); } } System.out.println("The entered matrix:"); for(int i = 0; i < rows; ++i) { for(int j...

  • Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895...

    Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895    {        public static void header()        {            System.out.println("\tWelcome to St. Joseph's College");        }        public static void main(String[] args) {            Scanner input = new Scanner(System.in);            int d;            header();            System.out.println("Enter number of items to process");            d = input.nextInt();      ...

  • Given java code is below, please use it! import java.util.Scanner; public class LA2a {      ...

    Given java code is below, please use it! import java.util.Scanner; public class LA2a {       /**    * Number of digits in a valid value sequence    */    public static final int SEQ_DIGITS = 10;       /**    * Error for an invalid sequence    * (not correct number of characters    * or not made only of digits)    */    public static final String ERR_SEQ = "Invalid sequence";       /**    * Error for...

  • *This needs comments for each line of code. Thanks in advance!* import java.util.Scanner; public class LabProgram...

    *This needs comments for each line of code. Thanks in advance!* import java.util.Scanner; public class LabProgram {     public static void main(String[] args) {         Scanner scnr = new Scanner(System.in);         int numCount = scnr.nextInt();         int[] Array = new int[numCount];                for(int i = 0; i < numCount; ++i) {             Array[i] = scnr.nextInt();         }         int jasc = Array[0], gws = Array[1], numbers, tempo;         if (jasc > gws) {             tempo = jasc;             jasc...

  • I need a java flowchart for the following code: import java.util.*; public class Main {   ...

    I need a java flowchart for the following code: import java.util.*; public class Main {    public static void main(String[] args) {    Scanner sc=new Scanner(System.in);           System.out.print("Enter the input size: ");        int n=sc.nextInt();        int arr[]=new int[n];        System.out.print("Enter the sequence: ");        for(int i=0;i<n;i++)        arr[i]=sc.nextInt();        if(isConsecutiveFour(arr))        {        System.out.print("yes the array contain consecutive number:");        for(int i=0;i<n;i++)        System.out.print(arr[i]+" ");       ...

  • //Your programs should not crash under any circumstances. import java.util.Scanner; public class LetterCount { public static...

    //Your programs should not crash under any circumstances. import java.util.Scanner; public class LetterCount { public static int countBs(String word) { for (int i = 0; i < word.length(); i++) { int counter = 0; if ((word.charAt(i) == 'b') || (word.charAt(i) == 'B')) { counter++; } } return counter; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Please enter a word: "); String str = in.next(); int result = countBs(str); System.out.printf("%s contains letter B %d times.\n", str,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT