简体   繁体   中英

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?

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

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

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.

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