简体   繁体   中英

Reading integers separated by semicolon from a file in C++

For a lab assignment we have been given a data file that looks like this:

12; 5;
15; 14;
21; 1;
1; 22;

The idea is to extract the first two integers and add them together. Nothing I've tried has been able to extract the second number (5) from the file. So far this is what I've got:

void add_numbers()
{
    std::ifstream in("fileio-data-1.txt");
    if (!in) {
        std::cerr << "Could not open file, exiting." << std::endl;
        exit(1);
    }

    int num1;
    int num2;


    in >> num1;
    std::cout << num1 << std::endl;
    in >> num2;
    std::cout << num2 << std::endl;

    std::cout << num1 + num2 << std::endl;

}

num1 has no issues and is always output as 12 but num2 ends up as 0. I've tried using num1 = in.get() and num2 = in.get() but that gives values of num1 = 49 and num2 = 50. I know I'm missing something here, but I can't figure out what it is.

The simple answer is to add a char variable to read the semi-colons,

int num1, num2;
char semi;
std::cin >> num1 >> semi >> num2 >> semi;

The word you're looking for "extracting data" is "parse". (This will help you google search for similar issues in the future I believe)

To continue along your same line of thinking with what you've already got (using a stream), I think you'll need to loop through each character, comparing it with the output you need, similar to @john's answer.

int num1, num2;
char semi;

while (in >> num1 >> semi >> num2 >> semi){
    int sum = num1 + num2;
    cout << sum << "\n";
}

I find myself parsing text input lines a lot so I created the following utility function (probably influenced from my Perl scripting):

#include <algorithm>
#include <string>
#include <vector>

std::vector<std::string> split(const std::string& str, char delim) {
    std::vector<std::string> strings;
    size_t start;
    size_t end = 0;
    while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
        end = str.find(delim, start);
        strings.push_back(str.substr(start, end - start));
    }
    return strings;
}

and then you can split of each line using ; as a delimiter

std::string line;
while (std::getline(in, line)) {
    std::vector<std::string> str = split(line, ';');
    // could validate str[0] and str[1] here
    int num1 = std::stoi(str[0]);
    int num2 = std::stoi(str[1]);
    std::cout << (num1 + num2) << std::endl;
}

and as a bonus you can validate the strings to make it more robust in the face of bad input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM