0

Hey I am quite new to C++ and I am facing a problem:

I have a textfile which looks like this:

500

1120

10

number1,1 number1,2   ...   number1,500

number2,1

.

.

number1120,1

So the first two values on top of the text-file describe the dimensions of the matrix. I now want to write a code, which reads all the files from the matrix into an array or vector of int values. I can read the first three values (500, 1120,10) and write them into an integer value using getline and stringstream, but I can't figure out how to read the matrix tap separated with a loop.

1
  • You should provide a small example of what you've done so far to solve the problem. It is explained here stackoverflow.com/help/mcve Commented Jan 10, 2018 at 14:12

2 Answers 2

2

Something like this:

#include <iostream>
#include <sstream>

// Assume input is 12,34,56. You can use 
// getline or something to read a line from
// input file. 
std::string input = "12,34,56";

// Now convert the input line which is string
//  to string stream. String stream is stream of 
// string just like cin and cout. 
std::istringstream ss(input);
std::string token;

// Now read from stream with "," as 
// delimiter and store text in token named variable.
while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}
Sign up to request clarification or add additional context in comments.

2 Comments

A bit of explanation would be an incentive for me to upvote your answer ;) + OP's values are tab-separated (but this is a detail).
I added comments to code. If you have any specific question feel free to ask me.
0

You may consider to read the matrix line by line with a loop, and split the current line using a tokenizer (e.g. std::strtok) or a nested loop that splits the line at your delimiters. There is a thread about tokenizers.

Comments

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.