Home > Mobile >  printf moves cursor to the beginning of the line
printf moves cursor to the beginning of the line

Time:01-24

I have the following snippet which I'm trying to log into the terminal for debug purposes:

void DebugVector(vector<string> word_list) {
  size_t word_count = word_list.size();
  for (int i = 0; i < word_count; i  ) {
    for (int j = 0; j < word_count; j  ) {
      if (i == 156 && j == 156) {
        fflush(stdout);
        printf("We're supposed to find the word with value lares; ");
        fflush(stdout);
        const char *wordi = word_list[i].c_str();
        const char *wordj = word_list[j].c_str();
        printf("Actual values are %s and %s", wordi, wordj);
        fflush(stdout);
      }
    }
  }
}

I'm using Windows with the Windows Subsystem for Linux feature turned on and when I'm building the program with the following command

cl.exe /Zi /EHsc /nologo /Fe: C:\Users\user\Documents\VSCode_projects\test_program\main.exe C:\Users\user\Documents\VSCode_projects\test_program\main.cpp

and after I run it, the output is

We're supposed to find the word with value lares; Actual values are lares and lares

However, when I'm running it from the bash terminal in Windows, after building it with the following command:

$ g main.cpp -o main-linux.exe && ./main-linux.exe

The output is

and laresosed to find the word with value lares; Actual values are lares

It looks like the cursor is moved to the beginning of the line right after printing the first string. From what I understand c_str only outputs null terminated values, so I don't understand why this could happen.

I've tried creating a concatenated string, using cout instead, and I'm getting pretty much the same result. Also, the word_list has about 10,000 words in it, so I believe I'm not accessing any out of range values.

Is there anything that I can do here to make the program output the correct value?

CodePudding user response:

The issue was from the difference getline() makes when compiled with g and cl.exe. The vector was generated via this code:

if (list_file.is_open()) {
    while (getline(list_file, line)) {
      word_list.push_back(line);
    }
  }

getline() deals with new line in windows differently which is not very surprising. g will read the word including the carriage return (\r) value while cl.exe won't. This results in the print issue.

CodePudding user response:

you can't access vector elements with subscript like array because its object and it has address storage values

instead use .at() method of vector https://www.geeksforgeeks.org/vector-in-cpp-stl/ here in the element access method

and c_str() here works fine! no issue with that...

  •  Tags:  
  • Related