Odd symbols in terminal when running program - c++

The whole point of this program is to read a list of instructions from a file . On the first pass through I'm just getting the commands on the far left (the only ones without a \t) in front of them. I've managed to do that but the problem I'm running into, while I was testing my code to see if I had copied the char array over correctly, is that I'm getting really odd characters to the left side of my output.
Here is the original file I'm reading from: # Sample Input
LA 1,3
LA 2,1
TOP NOP
ADDR 3,1
ST 3, VAL
CMPR 3,4
JNE TOP
P_INT 1,VAL
P_REGS
HALT
VAL INT 0
The odd output I'm receiving however is:
D
D
D
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DVAL
D
D
I'm just not sure how I'm getting such a weird output. Here's my code:
#include <string>
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <fstream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
// If no extra file is provided then exit the program with error message
if (argc <= 1)
{
cout << "Correct Usage: " << argv[0] << " <Filename>" << endl;
exit (1);
}
// Array to hold the registers and initialize them all to zero
int registers [] = {0,0,0,0,0,0,0,0};
string memory [16000];
string symTbl [1000][1000];
char line[100], label[9];
char* pch;
// Open the file that was input on the command line
ifstream myFile;
myFile.open(argv[1]);
if (!myFile.is_open())
{
cerr << "Cannot open the file." << endl;
}
int counter = 0;
int i = 0;
while (myFile.good())
{
myFile.getline(line, 100, '\n');
if (line[0] == '#')
{
continue;
}
if ( line[0] != '\t' && line[0]!=' ')
{
pch = strtok(line-1," \t\n");
strcpy(label,pch);
}
cout << label<< endl;
}
return 0;
}
Any help would be greatly appreciated.

Maybe you missed the else case for if ( line[0] != '\t' && line[0]!=' '), where you need to give some value to label before printing.

One major problem is that you do not initialize the label array, so it can contain any random data, which you then print out. Another problem is that you print the label each iteration, even when you don't get a new label.
There are also a couple of other problems with your code, like not checking if strtok returns NULL, and you should really use while (myFile.getline(...)) instead of while (myFile.good()).
The best way to find out what the cause of your main problem is, is to run your program in a debugger, and step through it line by line. Then you will see what happens, and can examine variables to see if their content is what it should be. Oh, and stop using character arrays, use std::string as much as you can.

Related

g++ printed undesired 00000, why?

Below is my code;
int main(){
ifstream infile;
infile.open(fin);
ofstream outfile;
outfile.open(fout);
char c;
int input_order = 0;
string comp_str = "";
vector <string> pfx_str;
srand(time(NULL));
if (infile.fail())
{
cout << "cannot open file!" << endl;
return 0;
}
while (!infile.fail())
{
cout << input_order << endl;
c = infile.get();
if (c == '\n')
{
if (strcmp(comp_str.c_str(), "") != 0)
{
pfx_str.push_back(comp_str);
}
int num = rand() % pfx_str.size();
while (num == 0)
{
num = rand() % pfx_str.size();
}
for (int i = 0; i < num; i++)
{
outfile << "/" << pfx_str.at(i);
}
outfile << "\n";
input_order++;
pfx_str.clear();
}
else if (c == '/')
{
if (comp_str != "")
{
pfx_str.push_back(comp_str);
}
comp_str = "";
}
else
{
comp_str = comp_str + c;
}
}
infile.close();
outfile.close();
return 0;
}
For small set which consist of 10k inputs, it works.
However, for big set such as using 1600k inputs, it prints out 00000, and does not work. What makes it happened? and how to make it correctly working?
(Previously, I used this code for 1600k input and it works correctly....)
In compile, I used g++ -std=gnu++0x .....
I googled this issue but could not find out the right answer.. And also I could not figure out what this issue comes from....
Thanks,
+
This code is for randomly cutting the input.
This is the example of 1 input set; (to show the input pattern)
/aa/ab/bc/aaa/
Here, I consider 'aa', 'ab', 'bc', and 'aaa' as one component.
And I want randomly cut this input as components unit.
this is the brief step of the code;
1. generate the random number(except 0)
2. ex) I use the above input and the random number is 2.
then I cut this input and only '2' components is left, which is /aa/ab/
(repeat this procedure for each inputs in input text file
=> this input; /aa/ab/bc/aaa/
(inside, it generate random number 2)
output to be printed in output file; /aa/ab/
There is nothing wrong with your code.
I updated your code so that it compiles with g++:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(){
ifstream infile;
infile.open("fin.txt"); // substituted a real file name in here to test
ofstream outfile;
outfile.open("fout.txt"); // ditto here
...the rest is the same as what you put above.
named it test.cpp, and compiled it with:
g++ -lm test.cpp -o test.exe
I wrote a Ruby script to make the input file according to the test set you specified in the comments:
#!/usr/bin/env ruby
File.open( 'fin.txt', 'w') do |f|
1600000.times do
f << "/aa/ab/bc/aaa/\n"
end
end
I then ran the compiled program test.exe, and you totally owe me a beer for watching your line numbers go that high. This is time spent from my life for you that I will never get back. 😂
and got an expected fout.txt with
/aa
/aa/ab
/aa
/aa/ab
/aa/ab/bc
/aa/ab/bc
/aa/ab
/aa/ab/bc
/aa/ab
etc.
My guess is that your system's constraints are causing a system fault. I ran this on a typical desktop machine with a ton of memory, etc. If you're running it on an embedded system, it may not have similar resources. At this point, I was tempted to test on a Raspberry Pi, but I'm burning too much time on this already. Just know that there is nothing wrong with your code.
In the future, try to figure out what your coding problem is. Stack Overflow is super forgiving if you've really tried and can't figure out the solution, but you need to show what you've tried and what happened as a result. For problems that started out like this, where you think that you're trying to figure out an algorithmic problem, always give the data set and the unexpected result that occurred.
Good luck!

I continually get a "Bus Error" while this is code is being executed?

The purpose of this code is to take a file that has been passed into the program and generate the letter frequency of each letter in the file. In above code, I remove punctuation and convert to lowercase letters.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string fileContent = "qr rqh zrxog kdyh eholhyhg lq wkh odvw bhduv ri wkh qlqhwhhqwk fhqwxub wkdw wklv";
int count[26] = { 0 }; // an array the size of the alphabet.
for(int f = 0; f < fileContent.length(); f++) // run til the file end.
{
if(fileContent[f] == 32) // to take care of the spaces.
{
f++; // also tried "continue;" and yeild different and also incorrect results.
}
if(fileContent[f] >= 48 && fileContent[f] <= 57) //take care of numbers.
{
f++; // tried "continue;"
}
count[fileContent[f]]++;
}
for(int p = 0; p < 26; p++)
{
cout << char(p + 97) << ": " << count[p] << endl;
}
return 0;
}
When I run this code I get some accurate frequencies, and some horribly incorrect ones (seems like every other result is wrong, yet after a few letters it trails off into astronomically large numbers). Any way to do this better? what is wrong with this code? As per request I have added some more of the code (including a string with a random 100 in it) as it was apparently not clear enough)
For more context, this program is for a Ceasar shift decoder I'm working on. I am in basic c++ and would greatly appreciate any advise from you more experienced devs. thank you!
In your program, this statement:
count[fileContent[f]]++;
should be:
count[fileContent[f]-97]++; //Assuming that all alphabets are in lowercase
If you do not do -97, it is trying to increase the value at index fileContent[f] of count array, which may be beyond the limit of count array.
Also, make sure to continue in both the if blocks and you don't need to do f++ explicitly in both the if blocks as in the for loop you are already doing f++.
You are doing things the difficult way: using C-style arrays, magic numbers in your code, and risking buffer overflows everywhere.
Compare your code to this:
#include <string>
#include <iostream>
#include <map>
using namespace std;
int main()
{
string fileContent = "qr rqh zrxog kdyh eholhyhg lq wkh odvw bhduv ri wkh qlqhwhhqwk fhqwxub wkdw wklv";
map<char, int> counts;
for (char ch : fileContent)
++counts[ch];
for (char ch = 'a'; ch <= 'z'; ++ch)
cout << ch << ": " << counts[ch] << '\n';
}
Or to print all the map contents (if you do not want to print 0 for letters that did not occur) you can use:
for (auto& item : counts)
cout << item.first << ": " << item.second << '\n';
Exercise for the reader to add in the code to exclude the spaces and numbers. Hint: look up the cctype header.

Attempting to make a quine program in c++ using CodeBlocks [duplicate]

Wikipedia says it's called a quine and someone gave the code below:
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}
But, obviously you have to add
#include <stdio.h> //corrected from #include <stdlib.h>
so that the printf() could work.
Literally, since the above program did not print #include <stdio.h>, it is not a solution (?)
I am confused about the literal requirement of "print its own source code", and any purpose of this kind of problems, especially at interviews.
The main purpose of interview questions about quine programs is usually to see whether you've come across them before. They are almost never useful in any other sense.
The code above can be upgraded modestly to make a C99-compliant program (according to GCC), as follows:
Compilation
/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes \
-Wstrict-prototypes -Wold-style-definition quine.c -o quine
Code
#include <stdio.h>
char*s="#include <stdio.h>%cchar*s=%c%s%c;%cint main(void){printf(s,10,34,s,34,10,10);}%c";
int main(void){printf(s,10,34,s,34,10,10);}
Note that this assumes a code set where " is code point 34 and newline is code point 10. This version prints out a newline at the end, unlike the original. It also contains the #include <stdio.h> that is needed, and the lines are almost short enough to work on SO without a horizontal scroll bar. With a little more effort, it could undoubtedly be made short enough.
Test
The acid test for the quine program is:
./quine | diff quine.c -
If there's a difference between the source code and the output, it will be reported.
An almost useful application of "quine-like" techniques
Way back in the days of my youth, I produced a bilingual "self-reproducing" program. It was a combination of shell script and Informix-4GL (I4GL) source code. One property that made this possible was that I4GL treats { ... } as a comment, but the shell treats that as a unit of I/O redirection. I4GL also has #...EOL comments, as does the shell. The shell script at the top of the file included data and operations to regenerate the complex sequence of validation operations in a language that does not support pointers. The data controlled which I4GL functions we generated and how each one was generated. The I4GL code was then compiled to validate the data imported from an external data source on a weekly basis.
If you ran the file (call it file0.4gl) as a shell script and captured the output (call that file1.4gl), and then ran file1.4gl as a shell script and captured the output in file2.4gl, the two files file1.4gl and file2.4gl would be identical. However, file0.4gl could be missing all the generated I4GL code and as long as the shell script 'comment' at the top of the file was not damaged, it would regenerate a self-replicating file.
The trick here is that most compilers will compile without requiring you to include stdio.h.
They will usually just throw a warning.
A quine has some depth roots in fixed point semantics related to programming languages and to executions in general. They have some importance related to theoretical computer science but in practice they have no purpose.
They are a sort of challenge or tricks.
The literal requirement is just you said, literal: you have a program, its execution produces itself as the output. Nothing more nor less, that's why it's considered a fixed point: the execution of the program through the language semantics has itself as its ouput.
So if you express the computation as a function you'll have that
f(program, environment) = program
In the case of a quine the environment is considered empty (you don't have anything as input neither precomputed before)
You can also define printf's prototype by hand.
const char *a="const char *a=%c%s%c;int printf(const char*,...);int main(){printf(a,34,a,34);}";int printf(const char*,...);int main(){printf(a,34,a,34);}
Here's a version that will be accepted by C++ compilers:
#include<stdio.h>
const char*s="#include<stdio.h>%cconst char*s=%c%s%c;int main(int,char**){printf(s,10,34,s,34);return 0;}";int main(int,char**){printf(s,10,34,s,34);return 0;}
test run:
$ /usr/bin/g++ -o quine quine.cpp
$ ./quine | diff quine.cpp - && echo 'it is a quine' || echo 'it is not a quine'
it is a quine
The string s contains mostly a copy of the source, except for the content of s itself - instead it has %c%s%c there.
The trick is that in the printf call, the string s is used both as format and as the replacement for the %s. This causes printf to put it also into the definition of s (on the output text, that is)
the additional 10 and 34s correspond to the linefeed and " string delimiter. They are inserted by printf as replacements of the %cs, because they would require an additional \ in the format-string, which would cause the format- and replacement-string to differ, so the trick wouldn't work anymore.
Quine (Basic self-relicating code in c++`// Self replicating basic code
[http://www.nyx.net/~gthompso/quine.htm#links]
[https://pastebin.com/2UkGbRPF#links]
// Self replicating basic code
#include <iostream> //1 line
#include <string> //2 line
using namespace std; //3 line
//4 line
int main(int argc, char* argv[]) //5th line
{
char q = 34; //7th line
string l[] = { //8th line ---- code will pause here and will resume later in 3rd for loop
" ",
"#include <iostream> //1 line ",
"#include <string> //2 line ",
"using namespace std; //3 line ",
" //4 line ",
"int main(int argc, char* argv[]) //5th line ",
"{",
" char q = 34; //7th line ",
" string l[] = { //8th line ",
" }; //9th resume printing end part of code ", //3rd loop starts printing from here
" for(int i = 0; i < 9; i++) //10th first half code ",
" cout << l[i] << endl; //11th line",
" for(int i = 0; i < 18; i++) //12th whole code ",
" cout << l[0] + q + l[i] + q + ',' << endl; 13th line",
" for(int i = 9; i < 18; i++) //14th last part of code",
" cout << l[i] << endl; //15th line",
" return 0; //16th line",
"} //17th line",
}; //9th resume printing end part of code
for(int i = 0; i < 9; i++) //10th first half code
cout << l[i] << endl; //11th line
for(int i = 0; i < 18; i++) //12th whole code
cout << l[0] + q + l[i] + q + ',' << endl; 13th line
for(int i = 9; i < 18; i++) //14th last part of code
cout << l[i] << endl; //15th line
return 0; //16th line
} //17th line
Not sure if you were wanting the answer on how to do this. But this works:
#include <cstdio>
int main () {char n[] = R"(#include <cstdio>
int main () {char n[] = R"(%s%c"; printf(n, n, 41); })"; printf(n, n, 41); }
If you are a golfer, this is a more minified version:
#include<cstdio>
int main(){char n[]=R"(#include<cstdio>
int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}
My version without using %c:
#include <stdio.h>
#define S(x) #x
#define P(x) printf(S(S(%s)),x)
int main(){char y[5][300]={
S(#include <stdio.h>),
S(#define S(x) #x),
S(#define P(x) printf(S(S(%s)),x)),
S(int main(){char y[5][300]={),
S(};puts(y[0]);puts(y[1]);puts(y[2]);puts(y[3]);P(y[0]);putchar(',');puts(S());P(y[1]);putchar(',');puts(S());P(y[2]);putchar(',');puts(S());P(y[3]);putchar(',');puts(S());P(y[4]);puts(S());fputs(y[4],stdout);})
};puts(y[0]);puts(y[1]);puts(y[2]);puts(y[3]);P(y[0]);putchar(',');puts(S());P(y[1]);putchar(',');puts(S());P(y[2]);putchar(',');puts(S());P(y[3]);putchar(',');puts(S());P(y[4]);puts(S());fputs(y[4],stdout);}
/* C/C++ code that shows its own source code without and with File line number and C/C++ code that shows its own file path name of the file. With Line numbers */
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define SHOW_SOURCE_CODE
#define SHOW_SOURCE_FILE_PATH
/// Above two lines are user defined Macros
int main(void) {
/* shows source code without File line number.
#ifdef SHOW_SOURCE_CODE
// We can append this code to any C program
// such that it prints its source code.
char c;
FILE *fp = fopen(__FILE__, "r");
do
{
c = fgetc(fp);
putchar(c);
}
while (c != EOF);
fclose(fp);
// We can append this code to any C program
// such that it prints its source code.
#endif
*/
#ifdef SHOW_SOURCE_FILE_PATH
/// Prints location of C this C code.
printf("%s \n",__FILE__);
#endif
#ifdef SHOW_SOURCE_CODE
/// We can append this code to any C program
/// such that it prints its source code with line number.
unsigned long ln = 0;
FILE *fp = fopen(__FILE__, "r");
int prev = '\n';
int c; // Use int here, not char
while((c=getc(fp))!=EOF) {
if (prev == '\n'){
printf("%05lu ", ++ln);
}
putchar(c);
prev = c;
}
if (prev != '\n') {
putchar('\n'); /// print a \n for input that lacks a final \n
}
printf("lines num: %lu\n", ln);
fclose(fp);
/// We can append this code to any C program
/// such that it prints its source code with line number.
#endif
return 0;
}
main(a){printf(a="main(a){printf(a=%c%s%c,34,a,34);}",34,a,34);}

Output from array is wrong

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream &num, int (&array)[50]);
int main(){
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if(file.fail()){
cout << "The file failed to open.\n";
exit(1);
}
else{
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return(0);
}
void make_array(ifstream &num, int (&array)[50]){
int i = 0; // counter variable
while(!num.eof() && i < 50){
num >> array[i];
i = i + 1;
}
for(i; i>=0; i--){
cout << array[i] << "\n";
}
}
Alright, so this it my code so far. When I output the contents of the array, I get two really large negative numbers before the expected output. For example, if the file had 1 2 3 4 in it, my program is outputting -6438230 -293948 1 2 3 4.
Can somebody please tell me why I am getting these ridiculous values?
Your code outputs the array backwards, and also it increments i twice after it has finished reading all the values. This is why you see two garbage values at the start. I suspect you are misreporting your output and you actually saw -6438230 -293948 4 3 2 1.
You end up with the extra increments because your use of eof() is wrong. This is an amazingly common error for some reason. See here for further info. Write your loop like this instead:
while ( i < 50 && num >> array[i] )
++i;
Now i holds the number of valid items in the list. Assuming you do actually want to output them backwards:
while ( i-- > 0 )
cout << array[i] << "\n";
To output them forwards you'll need two variables (one to store the total number of items in the array, and one to do the iteration)
The check !num.eof() only tells you that the last thing you read was not eof. So, if your file was 1 2 3 4, the check will only kick in after the 5th num>>array[i] call. However, for that i, array[i] will be populated with a meaningless value. The only correct way to deal with eofs is to check for validity on every call to operator>>. In other words, the right condition is simply num>>array[i]. This works by exploiting this conversion to bool since C++11 and to void* pre-C++11.

C++ Do loop keeps doubling value when printing

I have a problem with do while loop which is escaped when user hit some key. I increase some value by 1 every time it loops. But when I'm printing this value (after every key press) the value is getting printed two times.
The code is as below:
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main () {
int x = 0;
char asd;
do {
x++;
asd = getch();
cout << x << " ";
} while(asd!=27);
system("pause");
return 0;
}
I need to check if the key has been pressed, but I dont know how to fix this issue with double printing every time key has been pressed.
Some help?
This is because getch() reads not only the character you do input, but also the new line feed.
You do actually write some_character and \n into the input stream. Both are characters and both are read.
You need to ignore rest of the stream, after the 1st character read.
Another thing it might be is that some keys generate two character codes "0 or 0xE0, and the second call returns the actual key code".
You can see what is really happening with something like this:
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main () {
int x = 0;
char asd;
do {
x++;
asd = getch();
cout << "Character code read: " << int(asd)
<< ", character count:" << x << "\n";
} while(asd!=27);
}
This will print actual key codes of what is read, so you will see what is going on.