0

I recently submitted an assignment that I had started using VS code and the Ubuntu WSL terminal and G++ compiler, but had to switch to Visual Studio 2019 because when I would output several strings on the same line, they would write over each other. The assignment had me read data from a file and place each element into an "ArrayList" (our self made vector class) of "Car" objects and output each cars elements to the user. We would also have to search through the list of cars to find cars of certain models and print all cars of that model. Not only could I not cout all of these elements on the same line, I could not compare elements (strings) with each other. Why would this only happen on Ubuntu? Why can't I clear the cout buffer with std::cout.flush(); or std::cout << std::flush;? Why can't I compare the elements to each other?

I have tried to flush the system in numerous ways (as I have found from other posts) such as: std::cerr, std::cout << std::flush;. The only thing that seems to work is if I use std::endl, however, I need these to be placed on the same line. I also cannot compare two strings using the == operand (or any other). Although, I can compare two int elements just fine.

Here is my (shortened) cars.data (.data was a requirement for the assignment) that held all the cars' elements that were to be stored into an "ArrayList":

1
Tesla
Model 3
Black
2
Chevrolet
Volt
Grey
3
Tesla
Model S
White
4
Nissan
Leaf
White
5
Toyota
Prius
Red

My implementation for storing each element into the "ArrayList":

    ArrayList cars_list(15);

    std::fstream cars;
    cars.open("cars.data");

    int tempID;
    std::string tempIDstr;
    std::string tempMake;
    std::string tempModel;
    std::string tempColor;

    if (cars.is_open())
    {
        for (int i = 0; !cars.eof(); ++i)
        {
            std::getline(cars, tempIDstr);
            tempID = std::stoi( tempIDstr );
            std::getline(cars, tempMake);
            std::getline(cars, tempModel);
            std::getline(cars, tempColor);

            Car tempCar(tempID, tempMake, tempModel, tempColor);

            std::cout.flush();
            std::cout << tempIDstr << " ";
            std::cout.flush();
            std::cout << tempMake << " ";
            std::cout.flush();
            std::cout << tempModel << " ";
            std::cout.flush();
            std::cout << tempColor << " " << std::endl;

            cars_list.push_back(tempCar);
        }
    }
cars.close();

And a function that I have used to compare strings to search the list:

void searchByMake(ArrayList list)
{
    std::string make;
    std::cout << "Enter the make you would like to search: ";
    std::cin >> make;
    std::cin.clear();
    std::cin.ignore(10000,'\n');

// Searching through the cars_list for the Make
    for (int i = 0; i < list.size(); ++i) 
    {  
        Car tempCar = list.get(i);
        if (make.compare(tempCar.getMake()) == 0)
        {
            std::cout << "ID:\t" << tempCar.getID() << "\n" 
                    << "Make:\t" << tempCar.getMake() << "\n" 
                    << "Model:\t" << tempCar.getModel() << "\n" 
                    << "Color:\t" << tempCar.getColor() << "\n\n";
        }
    }
}

The results of the first segment of code are (I noticed the spaces before each output):

 Black 3
 Greyvrolet
 White S
 Whitean
 Redusta

The expected output should look like:

1 Tesla Model 3 Black
2 Chevrolet Volt Grey
3 Tesla Model S White
4 Nissan Leaf White 
5 Toyota Prius Red

And whenever I try to compare strings the output returns a blank line:

Enter the make you would like to search: Tesla

Expected output would be:

Enter the make you would like to search: Tesla
id: 1
Make: Tesla
Model: Model 3
Color: Black

id: 3
Make: Tesla
Model: Model S
Color: White

My teacher mentioned that the issue may be with Ubuntu itself not being able to clear the buffer even when prompted to, but I still can't find a solution. FYI This is a passed assignment that I can no longer get credit for, this question is strictly out of curiosity and a desire to still use Ubuntu WSL as my development terminal.

  • Related: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Algirdas Preidžius Sep 18 '19 at 01:16
  • 3
    *"I would output several strings on the same line, they would write over each other"*... by chance did you create the file under windows and did it have an embedded `'\r'` (carriage return -- like the old typewriters -- that returned the carriage to the beginning position?) – David C. Rankin Sep 18 '19 at 01:17
  • 1
    This is a clear case of the input file using `\r\n` new line characters – Sam Varshavchik Sep 18 '19 at 01:22
  • Unless there's something really special going on, don't use `cout.flush`. Instead, if you really want to flush a line, just use `std::cout << std::endl` – selbie Sep 18 '19 at 01:23

1 Answers1

1

Do not control your read loop with !cars.eof() see: Why !.eof() inside a loop condition is always wrong.. The crux of the issue being after your last successful read with the file-position-indicator sitting immediately before end-of-file, no .eofbit() has been set on your stream. You then check !cars.eof() (which tests true) and you proceed.

You then call, e.g. std::getline 4-times never checking the return. The read fails on your very first std::getline(cars, tempIDstr); setting .eofbit(), but you have no way of detecting that, so you continue, invoking Undefined Behavior repeatedly attempting to read from a stream with .eofbit() set, and then using the indeterminate values in tempIDstr, etc.. as if they contained valid data.

Instead either loop continually checking the return of each input function used, or use the return of your read function as the condition in your read loop, for example you could do something similar to:

    std::ifstream f(argv[1]);    /* open file for reading */
    ...
    while (getline (f,tmp.IDstr) && getline (f,tmp.Make) && 
            getline (f,tmp.Model) && getline (f,tmp.Color))
        cars_list[n++] = tmp;

Above, your loop only succeeds if ALL of your calls to getline succeed and only then, if all succeed, is your data used in your cars_list.

Now on to your classic carriage-return problem. It is clear the file you are reading from contains DOS line-ending. For example, if you look at the actual contents of your input file, you will see:

Example Input File with DOS "\r\n" Line-Endings

Note the DOS line-endings denoted 0d 0a (decimal 13 10) "\r\n":

$ hexdump -Cv dat/cars_dos.txt
00000000  31 0d 0a 54 65 73 6c 61  0d 0a 4d 6f 64 65 6c 20  |1..Tesla..Model |
00000010  33 0d 0a 42 6c 61 63 6b  0d 0a 32 0d 0a 43 68 65  |3..Black..2..Che|
00000020  76 72 6f 6c 65 74 0d 0a  56 6f 6c 74 0d 0a 47 72  |vrolet..Volt..Gr|
00000030  65 79 0d 0a 33 0d 0a 54  65 73 6c 61 0d 0a 4d 6f  |ey..3..Tesla..Mo|
00000040  64 65 6c 20 53 0d 0a 57  68 69 74 65 0d 0a 34 0d  |del S..White..4.|
00000050  0a 4e 69 73 73 61 6e 0d  0a 4c 65 61 66 0d 0a 57  |.Nissan..Leaf..W|
00000060  68 69 74 65 0d 0a 35 0d  0a 54 6f 79 6f 74 61 0d  |hite..5..Toyota.|
00000070  0a 50 72 69 75 73 0d 0a  52 65 64 0d 0a           |.Prius..Red..|
0000007d

Your file has DOS "\r\n" line-endings. How does getline() work? By default getline() read up to the first '\n' character, extracting the '\n' from the input stream, but not storing it as part of the string returned. This leaves an embedded '\r' at the end of each string you store. Why does this matter? the '\r' (carriage-return) does just what its namesake says. Acting like an old typewriter, the cursor position is reset to the beginning of the line. (explaining why you see your output being overwritten -- it is) You write text until a '\r' is encountered and then the cursor is positioned back at the beginning of the line, what is written next overwrites what you just output there.

Instead your file should be a file with Unix/POSIX line-endings:

Example Input File with Unix/POSIX '\n' Line-Endings

Note the Unix/POSIX line-endings are denoted as 0a (decimal 10) '\n':

$ hexdump -Cv dat/cars.txt
00000000  31 0a 54 65 73 6c 61 0a  4d 6f 64 65 6c 20 33 0a  |1.Tesla.Model 3.|
00000010  42 6c 61 63 6b 0a 32 0a  43 68 65 76 72 6f 6c 65  |Black.2.Chevrole|
00000020  74 0a 56 6f 6c 74 0a 47  72 65 79 0a 33 0a 54 65  |t.Volt.Grey.3.Te|
00000030  73 6c 61 0a 4d 6f 64 65  6c 20 53 0a 57 68 69 74  |sla.Model S.Whit|
00000040  65 0a 34 0a 4e 69 73 73  61 6e 0a 4c 65 61 66 0a  |e.4.Nissan.Leaf.|
00000050  57 68 69 74 65 0a 35 0a  54 6f 79 6f 74 61 0a 50  |White.5.Toyota.P|
00000060  72 69 75 73 0a 52 65 64  0a                       |rius.Red.|
00000069

To see the effect let's look at a short example that reads your input file, both with Unix/POSIX line-endings and again with DOS line-endings to see the difference in action. The short example could be:

#include <iostream>
#include <fstream>

struct ArrayList {
    std::string IDstr, Make, Model, Color;
};

int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: insufficient input.\n" <<
                    "usage: " << argv[0] << " filename.\n";
        return 1;
    }

    std::ifstream f(argv[1]);
    ArrayList cars_list[15], tmp;
    size_t n = 0;

    while (getline (f,tmp.IDstr) && getline (f,tmp.Make) && 
            getline (f,tmp.Model) && getline (f,tmp.Color))
        cars_list[n++] = tmp;

    for (size_t i = 0; i < n; i++)
        std::cout   << " " << cars_list[i].IDstr 
                    << " " << cars_list[i].Make
                    << " " << cars_list[i].Model 
                    << " " << cars_list[i].Color << '\n';
}

Now let's look at the output if your file has Unix/POSIX line endings:

Example Use/Output

$ ./bin/arraylist_cars dat/cars.txt
 1 Tesla Model 3 Black
 2 Chevrolet Volt Grey
 3 Tesla Model S White
 4 Nissan Leaf White
 5 Toyota Prius Red

Now lets look at the output after reading the file with DOS line ending:

$ ./bin/arraylist_cars dat/cars_dos.txt
 Black 3
 Greyrolet
 White S
 Whiten
 Redusa

That looks curiously similar to the output you report. Hint, in WSL you should have a tool called dos2unix (which converts line-endings from DOS to Unix). Use it on your input file, e.g. dos2unix filename. Now re-run your program (after fixing your read loop) using the file as input and your problem should disappear.

(if you don't have dos2unix installed, then install it, e.g. sudo apt-get dos2unix)

Look things over and let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85