printf moves cursor to the beginning of the line - c++

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?

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.

you can access vector elements with subscripts like array
because its object and it has address storage values
YOU CAN ALSO 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...

Related

Command Line Input Encoding: Visual Studio/C++

Task: A text input as command-line argument is to be written to a file.
Issue: Some encoding conversion is happening somewhere, so the file doesn't contain the exact text which was input. e.g. s%3A_blabla becomes s:_blabla . (Some HTML kind of thing)
Environment: Visual Studio 2019, C++17
How is the command-line argument being supplied: Using Smart Command Line Arguments extension. Also read 'Edit 1'.
How is the input being processed:
I've tried two methods:
static std::vector<const char*> args;
for (size_t i = 0; i < __argc; i++)
{
args.push_back(__argv[i]);
};
..........
std::string filePath = "random.txt";
std::string final_write(args[i+1]); //some value of i is chosen using a for loop
std::cout<<final_write<<std::endl;//this will print "s:_blabla"
std::ofstream out(filePath);
out << final_write;
Second method:
#include <atlstr.h>
........
LPWSTR *szArgList;
int argCount;
szArgList = CommandLineToArgvW(GetCommandLineW(), &argCount);
for (int i = 0; i < argCount; i++)
{
CString pathCString(szArgList[i]);
std::cout<<pathCString<<std::endl; //Here also it prints "s:_blabla" for appropriate i
}
What I know:
I don't think cout is at fault, because in first case the file writing also give the same transformed output, and if I explicitly modify the string and add "%3A" to it, the cout is able to display that normally. I've not tried writing to file in the second case, as cout tells that something fishy has already happened during input.
It might be the extension, or an encoding issue somewhere else, I'm not sure. Any help?
Edit 1: As suggested, I checked the behaviour after removing the command line extension. I took input from Properties->Debugging section->Command Arguments, and I still face the same issue. Disabled the extension too.

Redirecting I/O only with <iostream> [Windows]

[#tl;dr] I have Visual Studio Ultimate 2013 and Eclipse Neon v2(C++),
and I need to redirect the output of my program using DOS format, but
I have no idea how.
Im on Windows btw.
OK.. so I have this class assignment where I have to write a program like this:
#include <iostream>
#include <string>
using namespace std;
/* Check if the Character is lower case or not */
bool checkLowerCase(char c) {
if (c >= 'a' && c <= 'z') return true;
return false;
}
/*
* If there is any lower case letter, it will replace it will a upper case.
* example:
* "Tauros" will become "TAUROS"
* "auHU" will become "AUHU"
*/
string fixer(string s)
{
char right = ('a' - 'A');
string a = s;
for (unsigned int i = 0; i < a.length(); i++)
{
if (checkLowerCase(a[i])) {
a[i] = a[i] - right;
}
}
return a;
}
int main(void)
{
while (1) //infinite loop
{
string line;
getline(cin, line);
if (!cin) { //Professor wants us to only check end of input like this
return 0;
}
line = fixer(line);
cout << line << endl;
}
}
The input was:
aaaaaa
bbbbbb
cccccc
The output was:
aaaaaa
AAAAAA
bbbbbb
BBBBBB
cccccc
CCCCCC
Thanks for reading this far. Ok, so here's my problem.
The output is all messed up, so I need to redirect the output somewhere else (at least for testing).
I know how to do that using , , holding each line in a Array of String, reallocating if needed and then print what is on the array, but, unfortunately, my lecturer demanded us only to include and
Ohh, I dont know if it will matter, but we may not use char*, only the class string.
My lecturer told us that we have to use DOS format. But I have no clue how to do that. If someone can tell me how to do either redirect the input or the output is finee...
I have in my PC both Eclipse C++ (working glitchy) and Visual Studio Ultimate 2013 (working fine).
[Edit] Im on Windows.
AGAIN: I may only include and
For more information, here's his slide on DOS format.
*For testing purposes one redirect to/from a file
*DOS formatting will have unexpected consequences
– The end-of-line is the CR-NL combination
– A line read from the file will end with CR
– The CR character is the command to erase the
previous line!
./main < infile.txt Input is from infile.txt
./main > outfile.txt Output is to outfile.txt
./main < infile.txt > outfile.txt Both input and output are redirected
OK, so... I found instructions that helped me here:
https://msdn.microsoft.com/en-us/library/ms235639.aspx
I opened my project folder in the VisualStudio, created 2 files.
input.txt
output.txt
I opened the Developer Command Prompt for VS2013 that I had in my PC.
cd ["C://my_project_path"] //go to my project folder
cl /EHsc file.cpp
/*
cl /EHsc will compile my program (I think it only compiles one file at a time.
I have yet to test it).
*/
file < input.txt > output.txt // this command will run my program
So when I run my program like this... Instead of waiting for an input from keyboard, my program will read input.txt as the standard input. And when I try to print something to the output, it will write on the output.txt instead.
[EDIT] at the end of the link I pasted, there are explanations on how to compile multiple files and what exacly does the /EHsc do exacly

C++ cout char 'return' character from file appears twice

I'm trying to create a program that encrypts files based on how Nazi Germany's Enigma machine worked, but without the flaw :P.
I have a function that gets a character at n point in a file, but when it returns a return character and I cout << it, it's like it hit enter twice.
IE if I loop cout-ing from i++ points in a file the individual lines in the terminal appear separated
by more returns
than one.
Here's the function:
char charN(string pathOf, int pointIn){
char r = NULL;
// NULL so I can tell when it doesn't return a character.
int sizeOf; //to store the found size of the file.
ifstream cf; //to store the Character Found.
ifstream siz; //used later to get the size of the file
siz.open(pathOf.c_str());
siz.seekg(0, std::ios::end);
sizeOf = siz.tellg(); // these get the length of the file and put it in sizeOf.
cf.open(pathOf.c_str());
if(cf.is_open() && pointIn < sizeOf){ //if not open, or if the character to get is farther out than the size of the file, let the function return the error condition: 'NULL'.
cf.seekg(pointIn); // move to the point in the file where the character should be, get it, and get out.
cf.get(r);
cf.close();
}
return r;
}
It works correctly if I use cout << '\n', but what's different about returns from a file and '\n'?
Or is there something else I'm missing?
I've been googling about but I can't find anything remotely similar to my problem, thanks in advance.
I'm using Code::Blocks 13.12 as my compiler if that matters.
Is this is on a windows machine? In windows new lines in text files are representing by \r\n.
\r = carriage return
\n = line feed
It's possible that you are couting each one separately and that the output buffer is creating a new line for each one.

cannot read the text file properly anymore

Alright so basically this is my program that reads a text file and place it inside of an array, in the end I printed out everything in that array. The program run fine and yielded the correct result few days. However, it just stopped working today. For instance the text file is
88
687
472
671
But upon the completion of the program the output is 0 1073741824 0 1073741824. I dont know what is going on and the only time I made some change to the bash was ulimit -s unlimited. Any idea?
int main(int argc, char *argv[])
{
ifstream file(argv[1]);
int placeholder;
int size = pow(2,atoi(argv[2]));
int array[size];
int index = 0;
while (file >> placeholder)
{
array[index]=placeholder;
index++;
}
for(int i = 0; i<size; i++)
{
cout<<array[i]<<endl;
}
return 0;
}
Are you sure your text-file is readable by the program? If the input file does not exist, the program will still try to print argv[2]**2 entries from array which does not contain any elements! The program ends up dumping garbage values.
I am also not sure why you do the pow call - why not get the number of elements from argv[2]?
Also, you use some c functions (atoi) when you could use C++ stringstream to do the conversion.
When I run your code with the input you provide, like this: ./a.out file.txt 2, it prints the 4 numbers as expected. When I do this instead: ./a.out does_not_exist.txt 2, it prints 4 garbage values and dumps them to the screen.

Using QString get strange characters in the output

int a=0;
while (a<2)
{
//infos.stops is point to one array, called abc[10]
output = output + QString::fromStdString(*infos.stops)+ "." ;
infos.stops++;
a++;
}
ui->showMsg->setText(output);
The problem is infos.stops did show, but some funny characters appear like:
I have uploaded all my source code which is designed in QT Designer
http://uploading.com/files/eaddfaf8/bus.zip/
The problem line is at manager.cpp line 133.
Try using
output = output + QString::fromStdString(*(infos.stops))+ "." ;
I think i solved it after a bit testing your application. The following code segment should do it:
output = output+ "Stops travelled: ";
for(int a = 0; a < infos._numstops; ++a)
{
if(a)
output += ", ";
output = output + QString::fromStdString(infos.stops[a]);
}
output = output + "<br>";
Note that you have the member infos._numstops availlable and should use it. The if(a) is a nice trick if you want to output a comma separated list.
(I ran your application and noticed that the info struct does not include the stop where you're starting your path but the one where it ends. You should include the starting stop in the output or exclude the target stop. Further note that the += operator like in the if-body is a common way to append strings.)
In manager.cpp:103 you are calling DE1.cost(X,Y). This method creates a std::string array (passed) on the stack (datzz.cpp:432) and at datzz.cpp:502 you do
c.stops = passed;
which stores a pointer to a memory block allocated on the stack in the stops variable of your DatzEzy::info instance c. When the method cost(string, string) returns, the memory allocated for passed is freed and your output will be garbage. Never store pointers to stack allocated objects.
By the way, you should consider using const references when passing (read-only) strings in function calls, which avoids expensive copying.