I have done a simple program testing pointers, references, and recursion.
Here is the code to overlook (the problem is complained to come from PassAddresses' function):
#include <iostream>
using namespace std;
long RecRecur(short &caps);
void PassAddresses(short &address, short &address2, const char *nosey);
int main(int args, char **LOC)
{
short test = 15;
const char rosey = 0;
short myLick = 500;
short PersonalWhim = 250;
const char *LOG = &rosey;
RecRecur(test);
PassAddresses(myLick, PersonalWhim, LOG);
}
void PassAddresses(short &address, short &address2, const char *nosey)
{
address = address + address;
address2 += address;
for(short i = 100; i < 1000; i++)
{
for(short c = 50; c != 120; c++)
{
cout << "These are just for-loop tests...." << /n;
}
}
cout << address << /n << address2 << /n << nosey << /n << &rosey;
}
long RecRecur(short &caps)
{
caps--;
if(caps > 0x7CDE)
{
RecRecur();
}
else return;
}
Basically the compiler is complaining that a "primary-expression" is expected before the "/" character, and I am clueless on what the issue could be. The expressions/operators on the "address" value are perfectly interchangeable.
1. The escape character is '\', not '/'.
cout << address << /n << address2 << /n << nosey << /n << &rosey;
change above line with
cout << address << "\n" << address2 << "\n" << nosey << "\n" << &nosey;
or
cout << address << endl << address2 << endl << nosey << endl << &nosey;
2. Notice that you have a type in the same line. You may want to write nosey not rosey :)
3. RecRecur(); takes an argument please give one.
4. RecRecur() has to return a long
The escape character '\', not '/'. It also needs to be inside quotes:
cout << "hello world" << '\n';
It's a simple syntax error - a newline is endl, not \n.
Related
I wrote a text cipher program. It seems to works on text strings a few characters long but does not work on a longer ones. It gets the input text by reading from a text file. On longer text strings, it still runs without crashing, but it doesn’t seem to work properly.
Below I have isolated the code that performs that text scrambling. In case it is useful, I am running this in a virtual machine running Ubuntu 19.04. When running the code, enter in auto when prompted. I removed the rest of code so it wasn't too long.
#include <iostream>
#include <string>
#include <sstream>
#include <random>
#include <cmath>
#include <cctype>
#include <chrono>
#include <fstream>
#include <new>
bool run_cypher(char (&a)[27],char (&b)[27],char (&c)[11],char (&aa)[27],char (&bb)[27],char (&cc)[11]) {
//lowercase cypher, uppercase cypher, number cypher, lowercase original sequence, uppercase original sequence, number original sequence
std::ifstream out_buffer("text.txt",std::ios::in);
std::ofstream file_buffer("text_out.txt",std::ios::out);
//out_buffer.open();
out_buffer.seekg(0,out_buffer.end);
std::cout << "size of text: " << out_buffer.tellg() << std::endl;//debug
const int size = out_buffer.tellg();
std::cout << "size: " << size << std::endl;//debug
out_buffer.seekg(0,out_buffer.beg);
char *out_array = new char[size + 1];
std::cout << "size of out array: " << sizeof(out_array) << std::endl;//debug
for (int u = 0;u <= size;u = u + 1) {
out_array[u] = 0;
}
out_buffer.read(out_array,size);
out_buffer.close();
char original[size + 1];//debug
for (int bn = 0;bn <= size;bn = bn + 1) {//debug
original[bn] = out_array[bn];//debug
}//debug
for (int y = 0;y <= size - 1;y = y + 1) {
std::cout << "- - - - - - - -" << std::endl;
std::cout << "out_array[" << y << "]: " << out_array[y] << std::endl;//debug
int match;
int case_n; //0 = lowercase, 1 = uppercase
if (isalpha(out_array[y])) {
if (islower(out_array[y])) {
//std::cout << "out_array[" << y << "]: " << out_array[y] << std::endl;//debug
//int match;
for (int ab = 0;ab <= size - 1;ab = ab + 1) {
if (out_array[y] == aa[ab]) {
match = ab;
case_n = 0;
std::cout << "matched letter: " << aa[match] << std::endl;//debug
std::cout << "letter index: " << match << std::endl;//debug
std::cout << "case_n: " << case_n << std::endl;//debug
}
}
}
if (isupper(out_array[y])) {
for (int cv = 0;cv <= size - 1;cv = cv + 1) {
if (out_array[y] == bb[cv]) {
case_n = 1;
match = cv;
std::cout << "matched letter: " << bb[match] << std::endl;//debug
std::cout << "letter index: " << match << std::endl;//debug
std::cout << "case_n: " << case_n << std::endl;//debug
}
}
}
if (case_n == 0) {
out_array[y] = a[match];
std::cout << "replacement letter: " << a[match] << " | new character: " << out_array[y] << std::endl;//debug
}
if (case_n == 1) {
std::cout << "replacement letter: " << b[match] << " | new character: " << out_array[y] << std::endl;//debug
out_array[y] = b[match];
}
}
if (isdigit(out_array[y])) {
for (int o = 0;o <= size - 1;o = o + 1) {
if (out_array[y] == cc[o]) {
match = o;
std::cout << "matched letter: " << cc[match] << std::endl;//debug
std::cout << "letter index: " << match << std::endl;//debug
}
}
out_array[y] = c[match];
std::cout << "replacement number: " << c[match] << " | new character: " << out_array[y] << std::endl;//debug
}
std::cout << "- - - - - - - -" << std::endl;
}
std::cout << "original text: " << "\n" << original << "\n" << std::endl;
std::cout << "encrypted text: " << "\n" << out_array << std::endl;
delete[] out_array;
return 0;
}
int main() {
const int alpha_size = 27;
const int num_size = 11;
char l_a_set[] = "abcdefghijklmnopqrstuvwxyz";
char cap_a_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char n_a_set[] = "0123456789";
std::cout << "sizeof alpha_set: " << std::endl;//debug
char lower[alpha_size] = "mnbvcxzasdfghjklpoiuytrewq";
char upper[alpha_size] = "POIUYTREWQASDFGHJKLMNBVCXZ";
char num[num_size] = "9876543210";
int p_run; //control variable. 1 == running, 0 == not running
int b[alpha_size]; //array with values expressed as index numbers
std::string mode;
int m_set = 1;
while (m_set == 1) {
std::cout << "Enter 'auto' for automatic cypher generation." << std::endl;
std::cout << "Enter 'manual' to manually enter in a cypher. " << std::endl;
std::cin >> mode;
std::cin.ignore(1);
std::cin.clear();
if (mode == "auto") {
p_run = 2;
m_set = 0;
}
if (mode == "manual") {
p_run = 3;
m_set = 0;
}
}
if (p_run == 2) { //automatic mode
std::cout <<"lower cypher: " << lower << "\n" << "upper cypher: " << upper << "\n" << "number cypher: " << num << std::endl;//debug
run_cypher(lower,upper,num,l_a_set,cap_a_set,n_a_set);
return 0;//debug
}
while (p_run == 3) {//manual mode
return 0;//debug
}
return 0;
}
For example, using an array containing “mnbvcxzasdfghjklpoiuytrewq” as the cipher for lower case letters, I get “mnbv” if the input is “abcd”. This is correct.
If the input is “a long word”, I get “m gggz zzzv” as the output when it should be “m gkjz rkov”. Sort of correct but still wrong. If I use “this is a very very long sentence that will result in the program failing” as the input, I get "uas” as the output, which is completely wrong. The program still runs but it fails to function as intended. So as you can see, it does work, but not on any text strings that are remotely long. Is this a memory problem or did I make horrible mistake somewhere?
For your specific code, you should run it through a memory checking tool such as valgrind, or compile with an address sanitizer.
Here are some examples of memory problems that most likely won't crash your program:
Forgetting to delete a small object, which is allocated only once in the program. A memory leak can remain undetected for decades, if it does not make the program run out of memory.
Reading from allocated uninitialized memory. May still crash if the system allocates objects lazily at the first write.
Writing out of bounds slightly after an object that sits on heap, whose size is sizeof(obj) % 8 != 0. This is so, since heap allocation is usually done in multiples of 8 or 16. You can read about it at answers of this SO question.
Dereferencing a nullptr does not crash on some systems. For example AIX used to put zeros at and near address 0x0. Newer AIX might still do it.
On many systems without memory management, address zero is either a regular memory address, or a memory mapped register. This memory can be accessed without crashing.
On any system I have tried (POSIX based), it was possible to allocate valid memory at address zero through memory mapping. Doing so can even make writing through nullptr work without crashing.
This is only a partial list.
Note: these memory problems are undefined behavior. This means that even if the program does not crash in debug mode, the compiler might assume wrong things during optimization. If the compiler assumes wrong things, it might create an optimized code that crashes after optimization.
For example, most compilers will optimize this:
int a = *p; // implies that p != nullptr
if (p)
boom(p);
Into this:
int a = *p;
boom(p);
If a system allows dereferencing nullptr, then this code might crash after optimization. It will not crash due to the dereferencing, but because the optimization did something the programmer did not foresee.
Here's the code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int keyArray[7] = {1,2,3,4,5,6,7};
int breakPoint;
int counter;
for (counter = 0; counter < 7; counter++)
{
// keyArray[counter] = (rand() % 9) + 1; later
keyArray[counter] = counter; //testing
}
cout << keyArray[0] + "\n";
cout << keyArray[1] + "\n";
cout << keyArray[2] + "\n";
cout << keyArray[3] + "\n";
cout << keyArray[4] + "\n";
cout << keyArray[5] + "\n";
cout << keyArray[6] + "\n";
cin >> breakPoint; //so I can see what the hell is going on before it disappears
return 0;
}
The only reason I gave values to keyArray was that I read in answer to a similar question that you have to initialize an array with data before you use it. But it made no difference. The output is just junk symbols whether you initialize or not.
The compiler is Visual Studio Community 2017. Thanks for any help.
The error is not in your logic but rather in your debugging output. Since the other answers focus on how to fix it, I'll rather explain what happens instead. There seems to be a misunderstanding about the way strings work in C++.
The failure is in this operation:
keyArray[0] + "\n"
Internally, string literals are arrays of characters, in this case const char[2], consisting of the newline and a terminating '\0' null terminator. When you then try to add the integer and this array together, the array will be represented by a pointer to its first element, i.e. it will decay to const char* in order to be used as the second argument to the plus operator used in your code.
So for the compiler, this line will need operator+(int, const char*). But the result of that will be const char*, the input pointer offset by the integer, as that is the operation that happens when adding integers to pointers.
So instead of printing the number and then the string, it will try to access a string that does not exist as the pointer now pointer behind the string "\n" and thus into some arbitrary memory.
Instead of doing
cout << keyArray[0] + "\n"
do:
cout << keyArray[0] << "\n"
or
cout << keyArray[0] << endl
You can't concatanate an integer with a string. That's why you got garbage output
Try this first:
cout << keyArray[0] << "\n";
If you are using compilers that support C++ 11 then try using std::to_string(...) to make a string from an integer before doing the addition:
cout << (std::to_string(keyArray[0]) + "\n");
you cannot concatenate int with string.
change
cout << keyArray[0] + "\n";
cout << keyArray[1] + "\n";
cout << keyArray[2] + "\n";
cout << keyArray[3] + "\n";
cout << keyArray[4] + "\n";
cout << keyArray[5] + "\n";
cout << keyArray[6] + "\n";
to
cout << keyArray[0] << "\n"
<< keyArray[1] << "\n"
<< keyArray[2] << "\n"
<< keyArray[3] << "\n"
<< keyArray[4] << "\n"
<< keyArray[5] << "\n"
<< keyArray[6] << endl;
You need to convert the integers into a string. Using a relatively recent version of C++:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int keyArray[7] = {1,2,3,4,5,6,7};
int breakPoint;
int counter;
for (counter = 0; counter < 7; counter++)
{
// keyArray[counter] = (rand() % 9) + 1; later
keyArray[counter] = counter; //testing
}
cout << std::to_string(keyArray[0]) + "\n";
cout << std::to_string(keyArray[1]) + "\n";
cout << std::to_string(keyArray[2]) + "\n";
cout << std::to_string(keyArray[3]) + "\n";
cout << std::to_string(keyArray[4]) + "\n";
cout << std::to_string(keyArray[5]) + "\n";
cout << std::to_string(keyArray[6]) + "\n";
cin >> breakPoint; //so I can see what the hell is going on before it disappears
return 0;
}
For the life of me I can't figure out why the I can't write to a c style string inside of a struct.
College student - can't use string class, haven't learned pointers.
Help? 2 hours at trying to figure this out.
#include <iostream>
using namespace std;
void strCopy(char from[], char to[])
{
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
}
struct card
{
char suit[20];
char rank[20];
int cvalue;
char location[20];
};
void printCard(card card)
{
cout << card.rank << " of " << card.suit << endl;
}
int main()
{
// I don't think strCopy()'s the problem, I've used it with my last project.
cout << "Test strCopy()" << endl;
char str1[14] = "abcdefghijklm";
char str2[14];
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
// Now the negative.
card one;
one.cvalue = 2;
strCopy("Somewhere", one.location);
strCopy("Two", one.rank);
strCopy("Hearts", one.suit);
printCard(one);
}
// I don't think strCopy()'s the problem, I've used it with my last
project.
Wrong
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
copies 255 characters, however that's not what you meant.
If here :
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
Your're getting "correct" output, then you're just unlucky, since that invokes an undefined behavior, an you're writing off the end of the array.
# include <iostream>
# include <ctime>
using namespace std;
int stripWhite(char *str);
int main ()
{
char str[50];
cout << "Enter a sentence . " << endl;
cin >>str;
cout << "Your sentence without spaces is : " << endl;
cout << (str) << endl; // This is my problem. The sentence only prints the first word
stripWhite(str);
cout << "There were " << stripWhite(str) << " spaces." << endl;
return 0;
}
int stripWhite(char *str)
{
char *p = str;
int count = 0;
while (*p)
{
if (*p != ' ')
count++;
{
*p++;
}
}
return count;
If you don't want to replace your function with the C++ string type, you can use cin.getline to get a c string (char array)
cin.getline(str, 50);
std::cin treats spaces as end of string indicators.
In order to get the full sentence use std::getline. since this expects a std::string as one of its parameters, you will have to adjust your stripWhite-function accordingly:
# include <iostream>
# include <string>
using namespace std;
int stripWhite(string str); //change the formal parameter's type
int main ()
{
string str;
cout << "Enter a sentence . " << endl;
getline(cin, str,'\n'); //use getline to read everything that has been entered till the press of enter
cout << "Your sentence without spaces is : " << endl;
cout << (str) << endl; // This is my problem. The sentence only prints the first word
stripWhite(str);
cout << "There were " << stripWhite(str) << " spaces." << endl;
system("pause");
return 0;
}
int stripWhite(string str)
{
int count = 0;
char* p = str.c_str;
while (*p)
{
if (*p != ' ')
count++;
{
*p++;
}
}
return count;
}
As pointed out by others, you should use std::getline instead of cin >> str.
However, there are multiple other problems in the code you provided.
Why use char array when you could use std::string ? Why are you so sure that 50 characters will be enough ?
Your stripWhite function doesn't seem to strip anything : you count the number of non-space characters, but you are not actually removing anything. Note that if you switch to std::string instead of plain of char arrays, you could use a standard algorithm to do the job (on the top of my head, I guess std::remove would be appropriate)
Assuming that stripWhite did actually modify the input string, why would you want to call it twice from your main ? If the goal is to strip the string in the first place, and then print the number of removed space, make stripWhite return the number of removed spaces and store this result in the main.
For example :
const int nbSpacesStripped = stripWhite(str);
cout << "There were " << nbSpacesStripped << "spaces." << endl;
Behold Boost String Algorithms and more particularly the replace/erase routines.
# include <iostream>
# include <string>
size_t stripWhiteSpaces(std::string& str)
{
size_t const originalSize = str.size();
boost::erase_all(str, ' ');
return originalSize - str.size();
}
int main ()
{
std::string str;
std::cout << "Enter a sentence . \n";
getline(std::cin, str);
size_t const removed = stripWhiteSpaces(str);
std::cout << "Your sentence without spaces is :\n";
std::cout << (str) << '\n';
std::cout << "There were " << removed << " spaces.\n";
system("pause");
}
My code:
Functionality: It is a function expects a three arguments and create a file.
void performLog(string strStoredProcName, int nCount, double time)
{
int tme=(int) time;
int hour=tme/3600;
tme=tme%3600;
int min=tme/60;
tme=tme%60;
int sec=tme;
char *StrLen;
int len = 0;
int lenpass = 0;
StrLen = &strStoredProcName[0];
len = strlen(StrLen);
lenpass = 41 - len;
fstream outFile( "Perform.out", ios_base::out | ios_base::app );
if ( ! outFile )
{
cerr << "Cannot open 'Perform.out' for output" << "\n" << endl;
exit(-1);
}
if (paramLogCreation == false)
{
outFile << "**************Performance Log*********************" << "\n" << endl;
outFile << "DB Type: MYSQL" << "\n" << endl;
outFile << "-----------------------------------------------------------------------------------------" << "\n" << "\t" << "\t" << "\t" << "\t" << "Stored Procedure Statitics" << "\n" << endl;
outFile << "-----------------------------------------------------------------------------------------" << "\n" << endl;
outFile << "Store Procedure Name" << setw(30) << "Execution Count" << setw(30) << "Time Taken to Execute" << "\n" << endl;
paramLogCreation = true ;
}
outFile << strStoredProcName << setw(lenpass) << nCount << setw(20) <<hour<<"::"<<min<<"::"<<sec <<"\n" << endl;
outFile.close();
}
Here i am writing a unit test cases, for the code , which i have written, This function is one of the functions in that.
Please help me , how to resolve this issue.
Please i am very new one to the C++ and need to know the where i committed mistake.
I think this is the error:
void performLog(string strStoredProcName, int nCount, double time)
[...]
char *StrLen;
[...]
StrLen = &strStoredProcName[0];
To convert a string to char*, you should use c_str:
StrLen = new char [strStoredProcName.size()+1];
strcpy (StrLen, strStoredProcName.c_str());
Assuming by string you mean std:;string then when you say:
StrLen = &strStoredProcName[0];
len = strlen(StrLen);
there is no guarantee that the proc name contains a null-terminated string for strlen() to work on. If you want the length of the string, use the size() member function:
len = strStoredProcName.size();
However, this should not cause the error message you are getting, so please indicate in your post where the error is!!!
It looks like the error you're getting is in the header file (DM_simtoolTest.h), not the source file, which you appear to have pasted into the question.
The compiler is complaining that your code tries to use a function pointer (that's the strange int (*)(int) syntax) to get a string. Without seeing the code in question, my first (wild, speculative) guess would be that you forgot to quote the name of the function you're trying to test. I'd need to see the source of the header as well to properly identify the problem.