1

Pretty simple really, I hope. I have opened a text file, and I want it to read the first line with getline. I want it to take all the integers in that line, separated by commas, and add them together to be stored in a variable. However, I'm not quite sure how to set this up with delimiters.

#include <fstream>
#include <iostream>

int main(){
        std::fstream codeBreaker;
        int x,y,z;
        codeBreaker.open("input.txt");
        void decipher();
        void encode();
        std::cout << "Have a nice day!" << std::endl;
        return 0;
}

void decipher(){

}

void encode(){

}
  • 2
    Does this answer your question? [Parsing comma-delimited numbers in C++](https://stackoverflow.com/questions/35684285/parsing-comma-delimited-numbers-in-c) or [Parsing a comma-delimited std::string](https://stackoverflow.com/questions/1894886/parsing-a-comma-delimited-stdstring) or [How can I read and parse CSV files in C++?](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – walnut Feb 14 '20 at 23:46
  • Kind of unusual to see function declarations inside a function. I recommend placing them before `main`. – Thomas Matthews Feb 15 '20 at 01:17
  • Try something like this: `getline(infile, line); std::istringstream data_stream(line); line >> number; line >> comma; line >> number2; //...` – Thomas Matthews Feb 15 '20 at 01:19

1 Answers1

0

You've already outlined the first step: read in the first line with std::getline. One point you've missed though is that almost anytime you read data you want to check whether the read succeeded.

std::string line;
if (std::getline(infile, line))
    // we got some data
else
    // the read failed

From there, you need to parse that line into individual numbers. One way to do that is with a stringstream.

std::stringstream buffer(line);

Since your numbers are separated by commas, you'll then need to read (but otherwise ignore) the comma, and then the next number. Continue until you reach the end of the line, which you'll typically find out by checking whether reading the number succeeded or not.

int number;
while (buffer >> number) {
    char ch;
    buffer.get(ch);
    if (ch != ',')
        // unexpected input ?
    // do something with the number we just read here
}
Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035