简体   繁体   中英

cout not printing string of vector after getline

I have a.csv file with following contents:

1.0,2.0
2.0,3.0

Now i want to read this file and print it to the terminal. I want the output look like this:

1.0|2.0|
2.0|3.0|

But all i get is:

|
|

When i run the debugger the vector contains the correct data but it just wont print it.

Vector array while cout (debugger):

array = {std::vector<std::vector>}
   [0] = {std::vector<std::basic_string, std::allocator>}
      [0] = {std::basic_string<char, std::char_traits, std::allocator>} "1.0"
      [1] = {std::basic_string<char, std::char_traits, std::allocator>} "2.0\r"
   [1] = {std::vector<std::basic_string, std::allocator>}
      [0] = {std::basic_string<char, std::char_traits, std::allocator>} "2.0"
      [1] = {std::basic_string<char, std::char_traits, std::allocator>} "3.0\r"

My code:

#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <fstream>

int main()
{
    using namespace std;

    ifstream in("C:\\Users\\freit\\CLionProjects\\Aufgabe2\\data.csv", ios_base::in);

    string line, field;

    vector< vector<string> > array;  // the 2D array
    vector<string> v;                // array of values for one line only

    while ( getline(in,line) )    // get next line in file
    {
        v.clear();
        stringstream ss(line);

        while (getline(ss,field,','))  // break line into comma delimited fields
        {
            v.push_back(field);  // add each field to the 1D array
        }

        array.push_back(v);  // add the 1D array to the 2D array
    }

    // print out what was read in

    for (size_t i=0; i<array.size(); ++i)
    {
        for (size_t j=0; j<array[i].size(); ++j)
        {
            cout.flush();
            cout << array[i][j] << "|"; // (separate fields by |)
        }
        cout << "\n";
    }

    return 0;
}

The problem is within the data.cls i wanted to read. The debugger shows an \r ( escape sequence ) at the end of every line. This might have appeared after opening data.cls with Excel and the autosave ticked. Problem was solved after writing a new data.cls with standard windows texteditor. Got the solution thanks to comments!

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