简体   繁体   中英

Reading tab-separated values from text file into array

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.

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';
}

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

Thanks for al the answers I can now read all the data, tabseperated into an array, but unfortunally I run into a very weired problem. So this is my code:

// Matrix deklarieren 
    long int** mat_dat = new long int *[m_height];
    for (long int a = 0; a < m_height; ++a)
        mat_dat[a] = new long int[m_width];

    //ganzes Feld als String einlesen


    //Daten aus Textdatei lesen
    long int i = 0;
    long int j = 0;
    long int value = 0;
    while (myfile.good())
    {
        getline(myfile, test);
        istringstream ss(test);
        string token;
        while (std::getline(ss, token, '\t'))
        {
            cout << token << '\t';
            value = atoi(token.c_str());
            mat_dat[j][i] = value;
            i++;
        }
        if (j == m_depth)
        {
            break;
        }
        j++;
        i = 0;

It safes all the data perfectly into the array, thats what I thought. But when I look closly only the first 512 values of the array are correct (mat_dat[0][512] are correct) and (mat_dat[1][512] are correct. The following values in the row from mat_dat[0][512] to mat_dat[0][1120] are incorrect. Do you have any clue why it is starting to becom incorrect right at that place ?

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