2

I know there are several C++ ways to load in values from a CSV, but I'm curious, how can I adapt this incorrect approach with the minimal changes necessary to make it work:

std::ifstream fileStream ("File.txt");    // File.txt reads "1,2,3"
short numbers[3];

for (short i = 0; i < 3; ++i)
    fileStream >> numbers[i];

Is there any way that I can do this using ifstream::operator>>, while keeping as conceptually close as possible to this implementation? Fix this code! :-)

Thanks! Believe it or not, this will be very helpful in a computational neutrino physics project I'm working on.

1 Answer 1

3

As a quick fix reading the comma into a temporary variable will let you get the data out of the file.

std::ifstream fileStream ("File.txt"); 
short numbers[3];
char delim;

fileStream >> numbers[0];
for (int i = 1; i < 3; ++i){
    fileStream >> delim;
    fileStream >> numbers[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hooray! I was assuming operator>> would just keep skipping along until it reached the next variable of the type being loaded, but it was getting hung up on the commas, as you said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.