Moody
Moody

Reputation: 833

Read numbers separated by comma and write them to a file separated by tab

Given an input file such as:

 5,6
 3,4
 4,7

I want to convert it to the following output where the numbers are separated by a tab:

 5  6
 3  4
 4  7

I have the following code which reads the input file and tries to write the output file:

std::ofstream outputFile("test.txt");

if (outputFile.is_open()) {

    while(std::getline(infile, line, ',')) {
        std::stringstream   linestream(line);
        int val1;
        int val2;

        linestream >> val1 >> val2;
        outputFile << val1 << "\t" << val2 << "\n";
    }
}

The problem is that my output file contains:

 1       -1431507824
 3       5
 6       6
 2       6

Can someone explain why this is happening?

Upvotes: 0

Views: 205

Answers (3)

amin saffar
amin saffar

Reputation: 2033

Because you add ',' as Explicit delimiting character.

and Here what's you want

int main(){
        std::ofstream outputFile("test.txt");
        std::istringstream input;
        input.str("5,6\n3,4\n4,7\n");
        string line;
        stringstream linestream;
            while(getline(input, line)) {
                std::stringstream   linestream(line);
                int val1;
                int val2;
                char comma;         
                linestream >> val1>> comma >> val2;
                outputFile << val1 << "\t" << val2 << "\n";
        }
}

Output:

5   6
3   4
4   7

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

With

std::getline(linestream, data, ',');

you read everything up to the first comma in the stream. This data is discarded by you.

Then when you do

linestream >> val1 >> val2;

you read the remaining value into val1, and then the extraction will fail for val2 since there's nothing more to read. That will lead val2 to be uninitialized and have an indeterminate value.

A simple solution is to simply convert the string in data (using std::stoi) and assign to val1 (since that's the value it contains), and then read the remaining value into val2. Something like

std::getline(linestream, data, ',');
val1 = std::stoi(data);
linestream >> val2;

With your edit, the above answer is only partially valid. The solution is basically the same though.

Upvotes: 1

yassin
yassin

Reputation: 652

You are delimiting by comma, thus only reading one value in the first call. One possible fix is to read a line up to newline and then explicitly read in the comma between the two values:

while(std::getline(infile, line)) {
    std::stringstream   linestream(line);
    int val1;
    int val2;
    char comma;
    linestream >> val1 >> comma >> val2;
    outputFile << val1 << "\t" << val2 << "\n";
}

Upvotes: 1

Related Questions