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.
Related
I'm making a program where a person can input a direction and in the if statement, it adds/subtracts x/y axis and it draws a line after it gets over. The problem is that for some reason, it only works at the first iteration and doesn't draw any more lines after that.
I added a cin >> x >> y to test it out but it only draws one line and doesn't draw anymore.
Initially, the choices were in a switch statement but I changed to if because I thought that was causing the error.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string.h>
#include <cairo.h>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace std;
char b = NULL;
char u = 'œ';
char d = 'd';
int main()
{
cairo_surface_t *surface = cairo_image_surface_create_from_png("background.png");
cairo_t *cr = cairo_create(surface);
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 5);
double x = 0, y = 240;
cairo_move_to(cr, x, y);
long int count = 0;
int cl = 0;
int crr = 0;
int choice = 0;
int n;
system("cls");
while (choice != 5)
{
cin >> x >> y;
cairo_line_to(cr, x, y);
cairo_stroke(cr);
cairo_surface_write_to_png(surface, "spiral.png");
cout << "Current no. of points are : " << count << "/4096" << endl;
cout << "Enter direction: \n" << endl;
cout << "1 - Top Left \t 2 - Up \t 3 - Top Right " << endl;
cout << "4 - Left \t 5 - Stop \t 6 - Right" << endl;
cout << "7 - Bot. Left \t 8 - Down \t 9 - Bot. Right" << endl << endl;
cout << "Enter you choice: ";
cin >> choice;
if (choice == 1)
cout << "Test";
else
{
//More choices include the direction the person needs to go and it subtracts/adds to the x/y part
cout << "How many times ?: ";
cin >> n;
for (int i = 1; i <= n; i++)
{
x++;
count++;
cl++;
if (cl == 256)
{
cl = 0;
crr++;
}
}
system("cls");
}
}
}
I expect it to draw lines to a particular direction. Say the person inputs right, it draws a line towards right and so on. But here, no lines get drawn at all (except if I add a cin >> x >> y at the start of the while loop, that draws one line and that's it, no more lines.)
This fails because there is no current point anymore. After cairo_stroke(cr);, you can add cairo_move_to(cr, x, y); and it should start drawing more lines in the way you expect. I think... I'm not quite sure what you are up to with this program.
am taking a class of C++ and been asked to write a program that reads integers from a file.
first request is to output all of the integers in one line
and the second request is to output the average of the integers
ive tried what has been written in the book, and when I try to cout the sum or the average, it output the addition number by number not just the total
how can I fix this? i want the simplest code possible, I dont want anything that we didnt take in class yet
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;
int main()
{
int num;
ifstream infile;
ofstream outfile;
outfile.open("Answer.txt");
infile.open("DataFile2.txt");
infile >> num;
while (infile)
{
outfile << num << " ";
infile >> num;
}
infile.close();
infile.open("DataFile2.txt");
int sum = 0;
while (infile)
{
double avg;
infile >> num;
sum = sum + num;
avg = sum / 14;
cout << endl << sum << avg;
}
}
There are a lot of mistakes in your code.You should declare the avg variable outside the while loop.Also, you should calculate the average and print it after the while loop has finished looping.Also you are dividing the sum by 14 (constant) which is not good, since you don't know how many integers are in the file.
The code should look something like this:
int sum = 0;
double avg;
while (infile) {
infile >> num;
sum = sum + num;
}
avg = sum / 14;
cout << endl << sum << avg;
I am trying to write a loop that validates user input, and then repeats if the input is bad. The input must be either a binary number (as a string) or a decimal number (as an int). I have seperate functions to validate this input, but they are not causing any trouble.
The problem arises when I select 1 or 2, and then willingly enter an invalid binary or decimal number. At this point, the do-while loop repeats successfully. The program prints another request for user input to cout, But when it comes time for the user to enter input, the program thinks that there is input in the console before I even enter anything. I believe this is a problem with whitespace/control characters in the buffer, but I am not sure how to fix it. I have tried using std::cin >> std::ws to clear any straggling white space, but no luck.
#include <iostream>
#include <string>
#include <limits>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::max;
using std::streamsize;
using std::string;
//int toDecimal;
//true is is binary
bool validateBinary(const string &binaryNumber){
for(int i = 0; i < binaryNumber.length(); i++){
if((binaryNumber[i] != 1) && (binaryNumber[i] != 0)){
return false;
}
}
return true;
}
//true if is decimal
bool validateDecimal(){
return cin;
}
int main() {
int conversionType = 0; //we initialize conversionType to a default value of 0 to ensure the copiler it will always have a value
bool isBinary = false;
bool isDecimal = false;
string binaryNumberInput;
int decimalNumberInput;
do {
if(conversionType == 0){
cout << "Enter 1 to convert binary to decimal," << endl;
cout << "2 to convert decimal to binary, " << endl;
cout << "or 3 to exit the program: ";
std::cin >> std::ws; //to clear any whitespace fron cin
cin >> conversionType; //upon a second iteration, this value is read in before a user input is given
}
if(!cin || (conversionType != 1 && conversionType != 2)){
cout << "Incorrect input." << endl;
cin.clear(); //clear the fail bit
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //used to ignore not-numeric input
}
cout << "You have selected option " << conversionType << "." << endl;
if(conversionType == 1){
cout << "Please enter a binary number: ";
cin >> binaryNumberInput;
isBinary = validateBinary(binaryNumberInput);
if(!isBinary){
cout << "The numbered you entered is not a binary number!" << endl;
conversionType = 0;
}
}
if(conversionType == 2){
cout << "Please enter a decimal number: ";
cin >> decimalNumberInput;
isDecimal = validateDecimal(); //true if succeeded, meaning is a number
if(!isDecimal){
cout << "The numbered you entered is not a decimal number!" << endl;
conversionType = 0;
}
}
}
while((conversionType != 1 && conversionType != 2) || (isBinary == isDecimal));
return 0;
}
Rather than debug your current program you might want to consider using the standard library to simply things
#include <iostream>
#include <string>
#include <bitset>
#include <climits>
#include <limits>
template<typename T>
void get(T& value)
{
while (!(std::cin >> value)) {
std::cout << "Invalid input\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
int main()
{
std::cout << "Enter 1 to convert binary to decimal,\n" <<
"2 to convert decimal to binary\n";
int option;
if (std::cin >> option) {
switch (option) {
case 1: {
std::bitset<CHAR_BIT * sizeof(unsigned long long)> bits;
get(bits);
std::cout << bits.to_ullong() << '\n';
break;
}
case 2: {
unsigned long long i;
get(i);
std::cout << std::bitset<CHAR_BIT * sizeof i>(i) << '\n';
break;
}
}
}
}
If you want this to loop you should be able to add it back in again easily enough.
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
I am a beginner with C++. I have a new project at work where I have to learn it, so I'm trying some things just to test my understanding. For this problem, I'm trying to read a file and then print it on screen. Super simple, just trying to get good at it and understand the functions that I'm using. I copied some text from a MS Word document into a notepad (*.txt) file, and I'm trying to read this *.txt file. All of the text in the word document is bolded, but other than that there are no 'unusual' characters. Everything prints out on the screen as it appears in the document except the bolded " - " symbol. This character is printed as the "u" with a hat character ("so called extended ASCII" code 150). I try to print out the integer value of this character in my array (which should be 150) but I get -106. I realize this signed integer has the same bits as the unsigned integer 150. My question is how to get the output to say 150? Here's my code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
unsigned char* input1;
int input1size = 57;
ifstream file("hello_world2.txt",ios::binary | ios::ate);
if (file.is_open()){
int size;
size = (int) file.tellg();
cout <<"This file is " << size << " bytes." << endl;
file.seekg(0,ios::beg);
input1 = new unsigned char[input1size];
file.read(input1, input1size);
cout << "The first " << input1size <<" characters of this file are:" << endl<<endl;
for (int i=0; i<input1size; i++) {
cout << input1[i];
}
cout<<endl;
}
else {
cout <<"Unable to open file" << endl;
int paus;
cin>>paus;
return 0;
}
file.close();
int charcheck = 25;
int a=0;
int a1=0;
int a2=0;
unsigned int a3=0;
unsigned short int a4=0;
short int a5=0;
a = input1[charcheck];
a1 = input1[charcheck-1];
a2 = input1[charcheck+1];
a3 = input1[charcheck];
a4 = input1[charcheck];
a5 = input1[charcheck];
cout <<endl<<"ASCII code for char in input1[" << charcheck-1 <<"] is: " << a1 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] is: " << a << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck+1 <<"] is: " << a2 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as unsigned int: " << a3 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as unsigned short int: " << a4 << endl;
cout <<endl<<"ASCII code for char in input1[" << charcheck <<"] as short int: " << a5 << endl;
int paus;
cin>>paus;
return 0;
}
Output for all this looks like:
This file is 80 bytes.
The first 57 characters of this file are:
STATUS REPORT
PERIOD 01 u 31 JUL 09
TASK 310: APPLIC
ASCII code for char in input1[24] is: 32
ASCII code for char in input1[25] is: -106
ASCII code for char in input1[26] is: 32
ASCII code for char in input1[25] as unsigned int: 4294967190
ASCII code for char in input1[25] as unsigned short int: 65430
ASCII code for char in input1[25] as short int: -106
So it appears "int a" is always read as signed. When I try to make "a" unsigned, it turns all the bits left of the eight bits for the char to 1's. Why is this? Sorry for the length of the question, just trying to be detailed. Thanks!
What you're dealing with is the sign-extension that takes place when the char is promoted to int when you assign it to one of your a? variables.
All the higher order bits must be set to 1 to keep it the same negative value as was in the smaller storage of the char.