In: Computer Science
Write a C++ or program that parses (and stores into a variable
of the correct type) a string into 4 fields separated by a colon
(:):
Field 1: A non-empty string value that does not contain a
colon
Filed 2: An odd integer, or empty
Filed 3: One of these values: red, orange, yellow, green, blue,
indigo, violet
Field 4: Another string value (may contain colon characters)
output:
Accept: sample:556989:green:Longer example string :) Reject (bad color): sample:556989:purple:Longer example string :)
A sample string is:
sample:556989:green:Longer example string :)
The main method should read sample strings, one line at a time,
from a file specified on the command line
(i.e., passed in via argv)
Code in C++
#include<iostream>
#include<math.h>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
//handle less arguments
if(argc<2){
cout<<"Please enter the input file in command line arguments"<<endl;
return 0;
}
//use ifstream to parse the file
ifstream infile(argv[1]);
string line;
//read line by line form the file
while (std::getline(infile, line))
{
string non_empty_string="", color="", final_string;
int val=0;
int i=0;
//read non_empty_string
while(line[i]!=':'){
non_empty_string+=line[i];
i++;
}
i++;
//check for empty integer
if(line[i]==':'){
val=-1;//we set this to -1 to indicate empty value
}
//read the integer
while(line[i]!=':'){
val=val*10+(line[i]-'0');
i++;
}
i++;
//read the color
while(line[i]!=':'){
color+=line[i];
i++;
}
i++;
//final string is the remaing part of the line
final_string = line.substr(i);
//chaeck for accept and reject
if(non_empty_string.size()>0 && (val==-1 || val%2==1) &&
(color=="red" || color=="orange" || color=="yellow" || color=="green" || color=="blue" || color=="indigo" || color=="violet")){
printf("Accept: %s\n", line.c_str());
}else{
if(non_empty_string.size()==0){
printf("Reject: (first field should be non-empty string without colon): %s\n", line.c_str());
}else if(val!=-1 && val%2==0){
printf("Reject: (integer should be odd or empty): %s\n", line.c_str());
}else{
printf("Reject: (bad color): %s\n", line.c_str());
}
}
}
return 0;
}
Sample Input/Output
Content in input.txt
Console Input/output