C program not working with errors related to C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I wrote this program for school, however I keep getting C++ related errors (apparently)
#include <stdio.h>
#define int NUM_OF_CHARS 51
void switch (char *c)
{
//Little Letters
if (((*c)>=97) && ((*c)<=122))
(*c)-=32;
//Capital Letters
if ((c>=65) && (c<=90))
(*c)+=32;
//*c>=5
if ((c>=53) && (c<=57))
(*c)=56;
//*c<5
if ((c>=48) && (c<=52))
(*c)=48;
}*/
int main() {
char string[51];
printf("PLease Enter a String \n");
scanf("%s", string);
printf("%s => ", string);
int i=0;
char s[51];
while((string[i]!= "\0") && (i < NUM_OF_CHARS))
{
s[i]=switch (string[i]);
i++;
}
printf("%s", s);
return 0;*/
}
I'm getting errors like /stray xxx in program and macro names must be identified.
I'm kind of new to C so I'd appreciate if you could point me out to what the errors in this code are. Thanks!!

#define int NUM_OF_CHARS 51
replace it with
#define NUM_OF_CHARS 51
also, you have used
void switch (char *c)
since switch is a keyword, you cannot use it as a function name.

There are many issues. You probably want the program below. The code compiles and works but it is still absolutly horrible, but it respects your intention.
Try to make it better.
BTW the characters contained in the string variable are also changed, is this intended ?
#include <stdio.h>
#define NUM_OF_CHARS 51 // removed "int"
char switchcase (char *c) // << we need to return a char not void
{ // << name changed to switchcase
// all c changed to (*c), BTW: *c without () would be OK too
//Little Letters
if (((*c) >= 97) && ((*c) <= 122))
(*c) -= 32;
//Capital Letters
else if (((*c) >= 65) && ((*c) <= 90))
(*c) += 32;
//*c>=5
else if (((*c) >= 53) && ((*c) <= 57))
(*c) = 56;
//*c<5
else if (((*c) >= 48) && ((*c) <= 52))
(*c) = 48;
return *c;
}
int main() {
char string[51];
printf("PLease Enter a String \n");
scanf("%s", string);
printf("%s => ", string);
int i = 0;
char s[51];
while ((string[i] != '\0') && (i < NUM_OF_CHARS))
{
s[i] = switchcase(&string[i]);
i++; //^ & was missing here
}
s[i] = '\0'; // << you forgot the zero terminator
printf("%s", s);
return 0; // << removed stray "*/"
}

switch is a reserved word and cannot be used as a function name.

Related

make in hex from unsigned char [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Suppose I have a piece of code like
unsigned char *tag = NULL;
tag = (unsigned char *)malloc(8);
memset(tag, 0, 8);
memcpy(tag, (const char *)"50C59390",8);
I have to send it as length 4. So I am trying to convert it in 4 byte hex like 0x50C59390.
unsigned char * buffer = (unsigned char *)calloc(4, sizeof(char));
int index,j = 0;
for(index = 0 ; index < 8; index++)
{
buffer[j] = (tag[index] & 0x0F) | (tag[++index]>>4 & 0xF0);
printf("%02X", buffer[j]);
j++;
}
I am trying above code. but its not working as required.
You can't just copy ascii characters as hex values. You need to convert them.
Something like:
unsigned char convert(unsigned char ch)
{
if (ch >= '0' && ch <= '9')
{
return ch -'0';
}
if (ch >= 'a' && ch <= 'f')
{
return ch -'a' + 10;
}
if (ch >= 'A' && ch <= 'F')
{
return ch -'A' + 10;
}
return 0; // or some error handling
}
and use it like:
for(index = 0 ; index < 8; index = index + 2)
{
buffer[j] = convert(tag[index]) << 4;
buffer[j] += convert(tag[index+1]);
printf("%02X", buffer[j]);
j++;
}
See it online here: https://ideone.com/e2FPCT
From your question I am not exactly sure whether you try to convert to or from a string. However, if you have C++11 available, you can use std::stoi() and std::to_string() for easy conversion:
int hex_value = std::stoi(tag, nullptr, 16)
Note how the third argument of std::stoi() denominates the base (in this case 16 for hexadecimal).

C++ How to output the letters or numbers from input of letters or numbers

So let's say we have the following case: for ”12323465723” possible answers would be ”abcbcdfegbc” (1 2 3 2 3 4 6 5 7 2 3), ”awwdfegw” (1 23 23 4 6 5 7 23), ”lcwdefgw” (12 3 23 4 6 5 7 23), in this case, the user will input numbers from 1 to 26, not divided by any space and the program itself will suggest 3 ways of interpreting the numbers, getting the most of the combinations from 1 to 26 these being the values from a to z
As you can see this is edited, as this is the last part of the problem, Thank you all who have helped me this far, I've managed to solve half of my problem, only the above mentioned one is left.
SOLVED -> Thank you
This involves a decision between 0 to 2 outcomes at each step. The base cases are there are no more characters or none of them can be used. In the latter case, we backtrack to output the entire tree. We store the word in memory like dynamic programming. This naturally leads to a recursive algorithm.
#include <stdlib.h> /* EXIT */
#include <stdio.h> /* (f)printf */
#include <errno.h> /* errno */
#include <string.h> /* strlen */
static char word[2000];
static size_t count;
static void recurse(const char *const str) {
/* Base case when it hits the end of the string. */
if(*str == '\0') { printf("%.*s\n", (int)count, word); return; }
/* Bad input. */
if(*str < '0' || *str > '9') { errno = ERANGE; return; }
/* Zero is not a valid start; backtrack without output. */
if(*str == '0') return;
/* Recurse with one digit. */
word[count++] = *str - '0' + 'a' - 1;
recurse(str + 1);
count--;
/* Maybe recurse with two digits. */
if((*str != '1' && *str != '2')
|| (*str == '1' && (str[1] < '0' || str[1] > '9'))
|| (*str == '2' && (str[1] < '0' || str[1] > '6'))) return;
word[count++] = (str[0] - '0') * 10 + str[1] - '0' + 'a' - 1;
recurse(str + 2);
count--;
}
int main(int argc, char **argv) {
if(argc != 2)
return fprintf(stderr, "Usage: a.out <number>\n"), EXIT_FAILURE;
if(strlen(argv[1]) > sizeof word)
return fprintf(stderr, "Too long.\n"), EXIT_FAILURE;
recurse(argv[1]);
return errno ? (perror("numbers"), EXIT_FAILURE) : EXIT_SUCCESS;
}
When run on your original input, ./a.out 12323465723, it gives,
abcbcdfegbc
abcbcdfegw
abcwdfegbc
abcwdfegw
awbcdfegbc
awbcdfegw
awwdfegbc
awwdfegw
lcbcdfegbc
lcbcdfegw
lcwdfegbc
lcwdfegw
(I think you have made a transposition in lcwdefgw.)
According to ASCII table we know that from 65 to 90 it A to Z.
so below is the simple logic to achieve what you're trying.
int main(){
int n;
cin>>n;
n=n+64;
char a=(char) n;
if (a>=64 && a<=90)
cout<<a;
else cout<<"Error";
return 0;
}
If you want to count the occurencs of "ab" then this will do it:
int main()
{
char line[150];
int grup = 0;
cout << "Enter a line of string: ";
cin.getline(line, 150);
for (int i = 0; line[i] != '\0'; ++i)
{
if (line[i] == 'a' && line[i+1] == 'b')
{
++grup;
}
}
cout << "Occurences of ab: " << grup << endl;
return 0;
}
If you want to convert an int to an ASCII-value you can do that using this code:
// Output ASCII-values
int nr;
do {
cout << "\nEnter a number: ";
cin >> nr;
nr += 96; // + 96 because the ASCII-values of lower case letters start after 96
cout << (char) nr;
} while (nr > 96 && nr < 123);
Here I use the C style of casting values to keep things simple.
Also bear in mind ASCII-values: ASCII Table
Hope this helps.
This could be an interesting problem and you probably tagged it wrong, There's nothing specific to C++ here, but more on algorithm.
First of all the "decode" method that you described from numerical to alphabetical strings is ambiguious. Eg., 135 could be interpreted as either "ace" or "me". Is this simply an oversight or the intended question?
Suppose the ambiguity is just an oversight, and the user will enter numbers properly separated by say a white space (eg., either "1 3 5" or "13 5"). Let nstr be the numerical string, astr be the alphabetical string to count, then you would
Set i=0, cnt=0.
Read the next integer k from nstr (like in this answer).
Decode k into character ch
If ch == astr[i], increment i
If i == astr.length(), set i=0 and increment cnt
Repeat from 2 until reaching the end of nstr.
On the other hand, suppose the ambiguous decode is intended (the numerical string is supposed to have multiple ways to be decoded), further clarification is needed in order to write a solution. For example, how many k's are there in "1111"? Is it 1 or 2, given "1111" can be decoded either as aka or kk, or maybe even 3, if the counting of k doesn't care about how the entire "1111" is decoded?

count vowels in a string with recursion function

I am currently in my last year of a BS in Information Systems with a major in programming. I took and passed C++ programming 1. I am now in C++ programming 2 and am having trouble with recursive functions. We have a homework assignment, where we are suppose to write a program that will count the number of vowels in a string that is entered by the user.
I have a program similar to this from my C++ programming 1 class that works using a for loop and if-then statements. I had assumed that it would be easy to convert this working program to use a recursive function, I was wrong.
I have the code (not looking for someone to do it for me) and I think i have it setup right. Just am not sure where to put the call to the function within the function.
Can somebody point me in the right direction?`
This is my first time asking a question. If i attached my code wrong, please let me know.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int vowelCount(string, int, int&);
int mail()
{
string input;
int len;
//int x;
//int y;
int count;
count = 0;
cout << "Enter a string of characters with no spaces: ";
cin >> input;
len = input.length();
vowelCount(input, len, count);
cout << "There were " << count << " vowels." << endl;
system("pause");
return 0;
}
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
if (len == 1)
{
count = count + 1;
return count;
}
else
{
y = input.at(len);
if ((y == 'a') || (y == 'e') || (y == 'i') || (y == 'o') || (y == 'u') || (y == 'A') || (y == 'E') || (y == 'I') || (y == 'O') || (y == 'U'))
{
count = count + 1;
len = len - 1;
}
else
{
len = len - 1;
vowelCount(string input, int len, int& count);
return count;
}
}
}
return 0;
}
For a general understanding, I recommend the answers to this question.
First of all, this code doesn't run: it has syntax errors. You shouldn't be asking for logic help until you have a program that at least runs. You cannot call a function with the entire signature. FOr instance, the final block should be a simple
return vowelCount(input, len-1)
You're returning the count as both the function's value and a parameter. Drop the parameter.
Now, for understanding the recursion ... take this in a couple of steps:
If the string is empty, return 0.
Otherwise, check the current letter:
2T if it's a vowel, return 1 + {count on rest of string}
2F else, return {count on rest of string}
Your two recursive calls are in the braces. Can you take it from here?
I would write the function the following way
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
std::string::size_type vowelCount( const std::string &input, std::string::size_type pos = 0 )
{
const char *vowels = "AEIOU";
return pos >= input.size()
? 0
: ( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
+ vowelCount( input, pos + 1 );
}
int main()
{
std::string s;
std::cin >> s;
std::cout << "There were " << vowelCount( s ) << " vowels." << std::endl;
return 0;
}
If for example to enter
AaBbCcDdEe
then the output will be
There were 4 vowels.
I suppose that the string does not contain embedded zero characters.:)
Otherwise you should substitute the condition
( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
for
( input[pos] != '\0' && std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
As for your function then if to write it syntactically valid it does not make sense due to for example this statement
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
^^^^^^^^^^^^^^^^^^
because according to the C++ Standard member function at
5 Throws: out_of_range if pos >= size().

Can anyone please explain this output with a slight modification in the usual getchar_unlocked function()? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wanted to change the general getchar_unlocked program to print the position of space when the second number is entered.So i introduced 2 more variables r and a, such that r gets incremented every time a non space character is input and a gets r's value when a space character is input. However, by the change i made only the first no. is getting stored in s and a garbage value is getting stored in a. Why so?
#include <cstdio>
#define getcx getchar_unlocked
using namespace std;
inline void scan( int &n, int &a) //extra parameter a added
{
n=0; int r=0;
char ch;
ch=getcx();
while (ch<'0' || ch>'9') //Inclusion of a !=' ' condition
{
if (ch==' ')
a=r;
else
r++;
ch=getcx();
}
while (ch>='0' && ch<='9')
{
r++;
n=10*n + ch -'0';
ch=getcx();
}
}
int main()
{
int t,s,a;
scan(t,a);
printf("%d\n",t);
scan(s,a);
printf("%d",s);
printf("%d",a);
return 0;
}
The scan function skips non-digits, then reads 1 or more digits as an integer into n, and finally skips a single non-digit character. In the first loop to skip non-digits, it counts the number of non-spaces read and stores that number into a whenever it sees a space. If it never sees a space, a will remain unmodified.
So if you give your program an input like 10 20 (with just a single space), that space will be skipped by the first call to scan (the non-digit after the number), and a will never be initialized.
If you want your scan routine to not skip the character after the number it reads, you need to call ungetc to put it back after reading it and discovering that it is not a digit.
You are assigning the value of r to pointer a with a=r;, should be *a=r; and you have similar problems with n=10*n + ch -'0'; should be *n=10*(*n) + ch -'0';. Never forget your function arguments ( int &n, int &a) make n and a pointers and will need to be dereferenced to assign values. In fact, in the original thread, I took the arguments to be pseudo-code (int &n, int &a), int actual implementation, I would do (int *n, int *a) and adjust the code accordingly.
Here is how I updated the original, this illustrates the pass by reference implementation:
#include <stdio.h>
#define getcx getchar_unlocked
/* input parser reads - sign, and any digits that follow */
inline void inp ( int *num )
{
int n = 0;
int sign = 1;
char ch = getcx();
/* get the sign */
while ( ch < '0' || ch > '9' )
{ if (ch == '-') sign = -1; ch = getcx();}
/* add each char read. n is accumulator, (n << 3) + (n << 1) is just n * 10 */
while ( ch >= '0' && ch <= '9' )
n = (n << 3) + (n << 1) + ch - '0', ch = getcx(); /* = n*10 + ch - 48 */
n = n * sign;
*num = n;
}
int main (void) {
int number = 0;
printf ("enter something containing nummbers\n");
inp (&number);
printf ("number: %d\n", number);
return 0;
}

Stack corruption in message-encoding program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to write a C++ program that creates a list of letters that will
be used to encode a message according to the following rules:
Input a word
Remove all repeating letters to form the modified word
Place the modified word at the beginning of the array
Fill the remainder of the list with any letters of the alphabet that were not used in the word working from A to Z. (Your list should have all 26 letters of the alphabet)
For example, if the user enters HELLO, the modified word would become HELO, and the list would become HELOABCDFGIJKMNPQRSTUVXYZ. The list must be stored in an array of CHARacters.
This is the code I've written:
#include <iostream>
using namespace std;
int main()
{
char a;
int b = 0;
char word[4] = "\0";
char alphabet[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char code[27];
cout << "Please enter a word:" << endl;
cin >> word;
for (int i = 0; i<3; i++)
{
if (word[i] == word[i - 1])
{
a = word[i];
word[i] = word[i + 1];
}
code[i] = word[i];
b++;
}
for (int o = 0; o<27; o++)
{
if (alphabet[o] == word[1] || alphabet[o] == word[2] || alphabet[o] == word[3] || alphabet[o] == word[0])
{
o++;
}
code[b] = alphabet[o];
b++;
}
cout << code;
return 0;
}
Unfortunately, I'm getting this error:
Run-Time Check Failure #2
Stack around the variable word was corrupted.
Secondly, my code works for 4 characters. How can I make it work for any word?
this is a simple way to do this assignment.
note that input word lenght should be smaller than 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[100]; // input word lenght should be smaller than 100
char used[26];
memset(used, 0, 26);
scanf("%s", word);
for (int i=0; i<strlen(word); i++)
{
// convert to uppercase
if (word[i]>='a' && word[i]<='z')
word[i] -= 'a'-'A';
// skip non-alphabetic characters
if (word[i]<'A' || word[i]>'Z')
continue;
// print this char only if it's not been printed before
if (!used[word[i]-'A'])
printf("%c", word[i]);
// set to 1 so that we don't print it again
used[word[i]-'A'] = 1;
}
// print all unused characters
for (int i=0; i<26; i++)
if (!used[i])
printf("%c", i+'A');
printf("\n");
return 0;
}