Here is my code. The list of characters that do not "work" and continue to say that they are palindromes if wrapped around the cin still say they are correct. The list of characters that don't work are:
single quotes, double quotes, commas, periods, forward slashes, back slashes, dashes, exclamation points, # symbols, # symbols, $ symbols, % symbols, ^ symbols, & symbols, * symbols (asterisk), equals symbols, + symbol
int main()
{
int k = 1;
int i;
int length, halflength;
int yesno = 1;
char string [81];
char end[81] = "END";
while (k = 1)
{
cout << "Please enter a string of characters. " << endl;
cout << "Enter \"END\" in all caps to exit the program." << endl;
cin.getline(string, 81);
if (strcmp(string, "END") == 0)
{
return 0;
}
length = strlen(string);
halflength = length / 2;
for (i = 0; i < halflength; i++)
{
if (string[i] != string[length - i - 1]) // comparing
yesno = 0;
break;
}
if (yesno) {
cout << "You have successfully entered a palindrome." << endl;
}
else
{
cout << "You have not entered a palindrome." << endl;
return main();
}
}
}
I am unsure how to fix this, as a palindrome can not only be a sequence of letters, but a sequence of characters. If there is an easier way to compare the lines, then I would appreciate the help, as I have spent some time being frustrated at this.
your program says,"You have successfully entered a palindrome." for mlaylam!
the problem is not having the break statement in the right place.
the block should be enclosed within braces, otherwise(as you've done), after checking the first character and last, the for loop will break thereby giving wrong result.
if (string[i] != string[length - i - 1]){ // comparing
yesno = 0;
break;
}
Related
In a small utility I'm writing, I want to read a file record and:
look for the presence of an XOR checksum in the form *XX, where XX are hex digits
replace it if it's incorrect
add one if it's not present
So far, I'm only to the point of reading the file and looking for the checksum. The problem I'm up against is that std::string::find is not finding the * I know to be present; it returns npos every time.
The find() is on line 37. The first line read into strInput is:
$GPGGA,14240.99,2732.581,S,15301.947,E,1,06,3,65,M,37,M,-1.0,0006*6E\n
Here's the code:
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter input file name:\n";
std::string strFileName = "";
std::getline(std::cin, strFileName);
std::cout << "Filename entered: " << strFileName << '\n';
FILE* fp;
int nErrCode = EXIT_FAILURE;
fopen_s(&fp, strFileName.c_str(), "r+");
if (!fp)
{
std::string strErr = "Failed to open " + strFileName;
perror(strErr.c_str());
return nErrCode;
}
rewind(fp);
std::string strInput;
strInput.reserve(100);
std::string::size_type n;
do
{
fgets(&strInput[0], 99, fp);
std::cout << strInput.c_str();
//n = 0;
n = strInput.find('*');
if (n != std::string::npos)
std::cout << "Found checksum at position " << n;
else
std::cout << "Did not find checksum";
} while (!feof(fp));
}
Thanks in advance.
I've debugged this and all is well up to the find(). At that point, I can see that the return value is npos, even though I can see the value of strInput and verify that it contains an asterisk.
I have a vector of strings, and I fill the first string in it manually character by character
vector <std::string> vec(6);
vec[0][0] = 'h';
vec[0][1] = 'e';
vec[0][2] = 'y';
cout << "vec[0] = " << vec[0] << "\n"
now I want to print the vec[0] which is supposed to be a string "hey" , but it prints empty space.
I can print only if I print it character by character also, like this
for(int i = 0 ; i<1 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
cout << vec[i][j];
}
cout << "\n";
}
Why I can't simply print the string as a whole.
vector <std::string> vec(6); gives you a vector of six empty strings. vec[0][0] = 'h'; is trying to assign the character h into the first slot of the first empty string, which is not legal, as the bracket operator can only replace existing characters. Use something like vec[0] += 'h' to append to the string.
I am somewhat new to c++, our class only went over debugging briefly. This is probably my 10th do over, I have been over it a week, have done plenty of research over the web and I just don't understand debugging enough to figure out how to fix my code. The program is supposed to real a file like this:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
When it reads the file it's supposed to output the student ids, what they answered on each question and the grade for each student. My problem is, I don't know much about debugging and VS keeps throwing an exception at the end of the code I provided. I am just learning how to use dynamic arrays so I know it has something to do with my use of them because I had the program working fine in my other c++ class but I had to change it around to use dynamic arrays for this project.
What's wrong with my program? I have researched the web and reread the chapters in the book over and over and I cannot figure it out.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstddef>
using namespace std;
// function prototypes
void readFile(ifstream& inFile);
char assignGrade(int score, int numQues);
int main()
{
int numQues = 20;
int numStud = 0;
string *studentIDs;
studentIDs = new string[numStud];
char *correctAnswers;
correctAnswers = new char[numStud];
char *studentAnswers;
studentAnswers = new char[numQues];
ifstream inFile;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
cout << "\nPlease Enter the Number of Students: ";
cin >> numStud;
cout << endl;
readFile(inFile);
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the space between the student ID and the answer
for (int j = 0; j < numQues; j++) // loop questions
{
studentAnswers[j] = inFile.get(); // get the student's answers
}// end for
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer equals correct answer
score += 2; // correct answer
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ')
score -= 1; // incorrect answer but not a blank
else if (studentAnswers[j] == ' ')
score = 0;
delete[] studentAnswers;
}// end for
if (score < 0)
score = 0; // don't allow for negative scores
cout << endl; // new line, housekeeping
char grade = assignGrade(score, numQues); // call assignGrade function
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
delete[] studentIDs;
system("pause");
return(0);
}
void readFile(ifstream& inFile)
{
inFile.open("Ch12_Ex2Data.txt"); // use inFile to open Ch8_Ex6Data.txt
if (!inFile) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file and try again!\n" << endl; // display error message
system("pause");
exit(1); // exit the program
}
} // end readFile function
char assignGrade(int score, int numQues)
{
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
return 'A';
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
return 'B';
else if (percentScore >= 0.7) // if score is greater than or equal to 70%, return C
return 'C';
else if (percentScore >= 0.6) // if score is greater than or equal to 60%, return D
return 'D';
else // any score lower thn 60%, return F
return 'F';
} // end assignGrade function
It keeps breaking here in the debugger:
static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right)
_NOEXCEPT
{ // assign an element
_Left = _Right;
}
// Redo Programming Exercise Six of Chapter Eight
// Using Dynamic Arrays -- C++ Advanced
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// function prototype
void readFile(ifstream& inFile, string fileName);
int main()
{
// variables, pointers and dynamic arrays
int numStud = 200; // stores the number of students, max students was 200
int numQues = 20; // stores the number of questions on test
string *studentIDs; // pointer variable for studentIDs dynamic array
char *correctAnswers; // pointer variable for correctAnswers dynamic array
correctAnswers = new char[numQues]; // correctAnswers dynamic char array
char *studentAnswers; // pointer variable for studentAnswers dynamic array
studentAnswers = new char[numQues]; // studentAnswers dynamic char array
char *fileName; // pointer variable for fileName dynamic char array
fileName = new char[25]; // fileName dynamic char array
ifstream inFile; // input stream variable inFile
// display message to explain the program
cout << "\nJames Flowers - Chapter 12 - Programming Exercise 2" << endl;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
// request file name for fileName dynamic char array
cout << "\nPlease Enter the File Name (Ch12_Ex2Data.txt): ";
cin >> fileName;
cout << endl;
// call readFile function to read the file
readFile(inFile, fileName);
// request number of students for studentIDs dynamic char array and some calculations
cout << "\nHow many students took this test? (4): ";
cin >> numStud;
cout << endl;
studentIDs = new string[numStud]; // create studentIDs dynamic char array
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the blank space
inFile.getline(studentAnswers, '/n'); // get the student's test answers
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer is correct
score += 2; // add 2 to score
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ') // incorrect answer but not blank
score -= 1; // subtract 1 from score
else if (studentAnswers[j] == ' ') // if question left blank
score -= 0; // nothing subtracted from score
studentAnswers[j] = ' '; // clear each indice for next student
}// end for
cout << endl; // new line, housekeeping
char grade = 0; // char variable grade initialized to 0
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
grade = 'A'; // grade = A
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
grade = 'B'; // grade = B
else if (percentScore >= 0.7) // if score is greater than or equal to 70%,
grade = 'C'; // grade = C
else if (percentScore >= 0.6) // if score is greater than or equal to 60%,
grade = 'D'; // grade = D
else // any score lower than 60%,
grade = 'F'; // grade = F
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
system("pause"); // pause for readability
return(0);
}// end main
// readFile function reads the file, if not displays error message
void readFile(ifstream& inFile, string fileName)
{
inFile.open(fileName); // use inFile to open input file
if (!inFile.is_open()) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file name and try again!\n" << endl; // display error message
system("pause"); // pause for readability
exit(1);
}// end if
} // end readFile function
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How would you be able to replace digits in a given number using basic c++. Example if the number is 23444 and you want to take the old digit 4 and replace is with a new digit 5 to get a new number 23555.
I have some work done below but when I enter the inputs, it ends up giving me an incorrect result.
cout << "Enter the number: " << endl;
cin >> number;
cout << "Enter the old digit: " << endl;
cin >> oldDigit;
cout << "Enter the newDigit: " << endl;
cin >> newDigit;
newDigit=oldDigit;
cout << Newnum << endl;
You can convert int to char* using itoa() and iterate over it to
check does it contain number. If it does, get 4's position and replace
it with 5.
I know you didnt work with strings, but it can be helpful in your case.
Simple code:
#include <string.h>
#include <iostream>
#include <stdlib.h>
int main(){
int numer;
std::cin>>numer;
char* str;
itoa(numer, str, 10);
for(int i = 0; i < strlen(str); i++){
if(str[i] == '4') str[i]='5';
}
}
If I understand you correctly, you don't just want to simply add 111, you want to treat the number as a string, then change elements in the array. Is that correct?
This may get you on the right track:
Convert an int to ASCII character
if you really want to use only int to do this, here is a working example (base on some of your code)
#include <iostream>
using namespace std;
int replaceDig( int num, int oldDigit, int newDigit)
{
if(num==0)return 0;
int digit = num%10;
if(digit==oldDigit)digit = newDigit;
return replaceDig(num/10,oldDigit,newDigit)*10+digit;
}
int main()
{
int num, newnum, oldDigit, newDigit;
cout << "Enter the number: " << endl;
cin >> num;
cout << "Enter the old digit: " << endl;
cin >> oldDigit;
cout << "Enter the newDigit: " << endl;
cin >> newDigit;
newnum = replaceDig(num, oldDigit, newDigit);
cout << newnum << endl;
return newnum; //do you really want to return this?
}
I have come up with a solution . Don't know if it contains bug or not. Please let me know.
int num = 23444 ,new_num = 0;
int mod;
int exponent = 0;
/**
* Now form the new number
*/
while ( num > 0 ) {
mod = num % 10;
num /= 10;
if ( mod == 4 ) // check whether this is the old digit or not
new_num += 5 * pow( 10 , exp); // replace with new digit
else
new_num += mod * pow(10 , exp); // otherwise no change
exp++;
}
num = new_num;
std::cout << num;
I hope this works for you -
std::string s = std::to_string(23444);
std::replace( s.begin(), s.end(), '4', '5');
int num = std::stoi(s);
int replaceDig( int num, int oldDigit, int newDigit) // replacing the old digits in a number with a new digit
{
int position = numDigits(num);
int remainder = num;
int currentDigit;
while (remainder >0)
{
currentDigit=(num/pow(10,position))%10;
if(currentDigit==oldDigit)
{
num = num - oldDigit*pow(10,position);
num = num + newDigit*pow(10,position);
}
remainder = remainder/10;
position--;
}
}
This is the general idea, I guess. I didn't try to compile it though. And of course, this version isn't really optimized and we could find some more efficient ways of doing it. Oh, and it doesn't work with negative numbers, but this should be quite easy to adapt.
I want to make a program where the user can input many numbers but the program will have to identify if the first four or five numbers is equal to the numbers I've set.
ex.
user inputs 0123456789
then if first 5 is equal to number I've set.
Like if ( 01234 = 02134). But all the numbers can be stored in a variable and be displayed again.
Is it possible? Thank you in advance.
this worked.
kind of.
My code is as follows:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main ()
{
int mnum [11];
int ctr;
for (ctr=0; ctr<=10; ctr++)
{
cout << "Enter your mobile number: ";
cin >> mnum [ctr];
}
cout << "Your mobile number is ";
if (mnum [3] == 1||2 && mnum [4] == 3||1)
{
for (ctr=0; ctr<=10; ctr++)
{
cout << mnum [ctr];
}
}
else
{
cout << "Sorry. Invalid mobile number prefix." << endl;
system ("pause");
return main ();
}
return 0;
}
but i have to enter each number. how to make it entr it in one go and still have the same results?
You can use modulus and integer division together to get the individual digits.
Here's a mocked up example that will get each digit of a number and print it individually (notice the output number is reversed because of how I am getting the digits):
int num = 123456;
while(num > 0) {
std::cout << num % 10 << ' ';
num /= 10;
}
Output:
6 5 4 3 2 1