Question

In: Computer Science

Validating Input file, So for my C++ assignment, my professor says we need to validate the...

Validating Input file,

So for my C++ assignment, my professor says we need to validate the Input File, Which means, if the line is missing a comma, one of the 3 information, or the string is a white line, it will ignore it. If the line has a white line, the program will correct it and will read in the line.

I will store these into an Array, and display them in First name, Last name, and Number of Votes vertical columned categories.

Apparently I skipped this part of the lecture and book, since he won't tell me exactly and keeps telling me to read the book. But the book shows me how to make arrays, take a file and put it into an array. He said using substr and find() or something like that.

This is a sample of the txt file. My question is, What do i use to be able to take only the names and number and place them into an array. Please explain what each line is doing, even it is not completely obvious. I am a complete beginner.

F=Michael,L=John,V=3342

F=Danny,L=Red,V=2003

F=Hillary,L=Clinton, V=1588

F=Albert,L=Lee,V=5332

F=Steven,L=JohnV=4429

Correct line for the reference: F=John,L=Smith,V=3342

The line errors that your program needs to detect, are as follows:

incorrect token / separator, example in line 5: F=Steven,L=JohnV=4429

(comma missing) – lines with this error need to be ignored

space in token, example in line 3: F=Hillary,X=Clinton, V=1622

lines with this error need to be read, error fixed, data included in your dataset

empty line, example in line 6 – empty lines need to be ignored

This is the sample of the getline code we are HAVE to USE and FOLLOW.

void readFile(Candidate candidates[]) {

string line;

ifstream infile;

infile.open("elections.txt");

while (!infile.eof()) {

getline(infile,line);

// your code here

}

infile.close();

}

I DO NOT NEED A WHOLE CODE, JUST THE FUNCTION EXPLAINED WHAT THE FUNCTION AND THE CODE IS DOING BY LINE.

Solutions

Expert Solution

#######################################
       elections.txt
#######################################
F=Michael,L=John,V=3342
F=Danny,L=Red,V=2003
F=Hillary,L=Clinton, V=1588
F=Albert,L=Lee,V=5332
F=Steven,L=JohnV=4429



#######################################
            main.cpp
#######################################
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <cstring>

using namespace std;

// trim a string, it removes any spaces at end and start of the string
string trim(string& str) {
    str.erase(0, str.find_first_not_of(' '));       //prefixing spaces
    str.erase(str.find_last_not_of(' ')+1);         //surfixing spaces
    return str;
}

// this method counts the occurrences of a character in string.
int countCharacter(string s, char c) {  
        int count = 0;

        for (int i = 0; i < s.size(); i++) {
                if (s[i] == c) {
                        count++;
                }
        }

        return count;
}

// this method converts a comma separated string to tokens
// it returns all tokens in form of a vector
vector<string> tokens(string s) {
        vector<string> result;

        // while string has a comma
        while(s.find(",") != string::npos) {
                // find index of comma in string
                int index = s.find(",");
                
                // break token till comma
                string token = s.substr(0, index);
                
                // remove the token from original string
                s = s.substr(index + 1);

                // remove space from start of token, and push to vector of tokens
                result.push_back(trim(token));
        }

        // if last token is now not empty, push that too on vector
        if(!s.empty()) {
                result.push_back(trim(s));
        }

        return result;
}

// this method parses the token which is in format:
// F=<firstName>
// L=<lastName>
// V=<Votes>
void parseToken(string s) {
        if(s[0] == 'F') {
                cout << "FirstName: " << s.substr(2) << endl;
        } else if(s[0] == 'L') {
                cout << "LastName: " << s.substr(2) << endl;
        } else if(s[0] == 'V') {
                cout << "Votes: " << s.substr(2) << endl;
        } 
}

// method to read the file and print the votes
void readFile() {

        // variable to read the line
        string line;

        // File variable to read input file
        ifstream infile;

        // open the file to read
        infile.open("elections.txt");

        // while input file has lines
        while (!infile.eof()) {

                // read a line from the file
                getline(infile,line);

                // Here comes the main logic to parse the line
                int commaCount = countCharacter(line, ',');

                if(commaCount != 2) {
                        // Ignore line,
                        cout << "Incorrect token separator: " << line << endl;
                } else if(line.empty()) {
                        // ignore empty line.
                } else {
                        // We now have a line which does contain correct commas
                        // and is not empty line.
                        for(string t: tokens(line)) {
                                parseToken(t);
                        }
                }
                cout << endl;
        }

        // close the file we opened
        infile.close();

}

int main() {
        readFile();
}



**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

Checking Input File for correct line format. So for my C++ assignment, my professor says we...
Checking Input File for correct line format. So for my C++ assignment, my professor says we need to validate the Input File, if there are white lines and spaces, in which it will ignore them, separated by a comma, and that all data items are there. This will be used in a program where i will store these into an Array, and display them in First name, Last name, and Number of Votes. This is a sample of the txt...
Checking Input File for correct line format. So for my C++ assignment, my professor says we...
Checking Input File for correct line format. So for my C++ assignment, my professor says we need to validate the Input File, if there are white lines and spaces, in which it will ignore them, separated by a comma, and that all data items are there. This will be used in a program where i will store these into an Array, and display them in First name, Last name, and Number of Votes vertical columned categories. This is a sample...
My professor says that through social media we should be able to make contact and speak...
My professor says that through social media we should be able to make contact and speak with anybody on the planet. He says everybody knows somebody that knows somebody that knows somebody. He said that we should be able to reach out to a person by knowing less than 5 people in the chain. How would I go about meeting a person like Lebron James? What would the process look like? I am trying to see if he is correct...
I'm having trouble with validating this html code. Whenever I used my validator, it says I...
I'm having trouble with validating this html code. Whenever I used my validator, it says I have a stray end tag: (tbody) from line 122 to 123. It's the last few lines. Thanks and Ill thumbs up whoever can help solve my problem. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <title>L7 Temperatures Fields</title> <!--    Name:    BlackBoard Username:    Filename: (items left blank for bb reasons    Class Section: (blank)    Purpose: Making a table to demonstrate my...
Hi, so for my homework assignment, we are meant to change this function so that instead...
Hi, so for my homework assignment, we are meant to change this function so that instead of making a list from the array going up in an ascending order, making it be listed in descending order, meaning going from largest number to smallest number, the code I have now works for the ascending order, but how would I change this for it to go descending? Any help would be amazing, and please with a tutorial, thanks so much. def heapify(arr,...
this is my matlab code for class, my professor commented "why is the eps an input...
this is my matlab code for class, my professor commented "why is the eps an input when it is set inside the function and not specified as a variable? how do i fix? function[] = () %Declare Global Variables global KS; global KC; KC = 0; KS = 0; End = 0; while (End == 0) choice = questdlg('Choose a function', ... 'Fuction Menu', ... 'A','B','B'); switch choice; case 'A' Program = 'Start'; while strcmp(Program,'Start'); Choice = menu('Enter the Trigonometric...
****NEED CODED IN C++, READ THE INSTRUCTIONS CAREFULLY AND PAY ATTENTION TO THE INPUT FILE, IT...
****NEED CODED IN C++, READ THE INSTRUCTIONS CAREFULLY AND PAY ATTENTION TO THE INPUT FILE, IT IS REQUIRED FOR USE IN THE PROBLEM**** You are to generate a list of customers to serve based on the customer’s priority, i.e. create a priority queue/list for a local company. The company has been receiving request and the request are recorded in a file, in the order the request was made. The company processes each user based on their priority, the highest priority...
I need C++ program that Read an input file of text.txt one word at a time....
I need C++ program that Read an input file of text.txt one word at a time. The file should consist of about 500 words. The program should remove all punctuations,keep only words. Store the words in a built-in STL container, such as vector or map.Can someone help with any additional comments that I can understand the logic?thank you
Please assist with getting my code to correctly check to validate input. Everything else works fine,...
Please assist with getting my code to correctly check to validate input. Everything else works fine, but when I enter a character, it should say Invalid entry. Everything else should also work. It should not allow more or less than 9 digits, and it should ask again for input if it doesn't like the input. Please help my code and explain how it is working. I also need to keep the recursive function. #include <stdio.h> #include <ctype.h > int SecNumSum(long...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have to add the below requirement of calculating the expected winning probability of VCU. Revisit the program you developed for Problem 3 of Assignment 2. Now your program must calculate the expected winning probability of VCU through simulation. Run the simulation 10,000 times (i.e., play the games 10,000 times) and count the number of wins by VCU. And then, calculate the winning probability by using...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT