I am new to programming and especially C++ so I decided to re-write a java program I wrote to convert a number (for example 13) to words (thirteen), and it worked fine but I tried re-writing it in C++ and after compiling, starting the program, and entering the number it does nothing. I am sorry if thing like my variable's names are unusual.
This is the java program:
public class Say
{
//AAAARRRRRR!!!! Here be Arrrrrrays!
static String first[] =
{
"" , "One " , "Two " , "Three ", "Four ", "Five " , "Six " ,
"Seven " , "Eight " , "Nine " , "Ten " , "Eleven " , "Twelve " ,
"Thirteen " , "Fourteen " , "Fifteen " , "Sixteen " , "Seventeen " ,
"Eighteen " , "Nineteen "
};
static String second[] =
{
"" , "" , "Twenty " , "Thirty " , "Fourty " , "Fifty " ,
"Sixty ", "Seventy " , "Eighty " , "Ninety "
};
static String sections[] =
{
"" , "Hundred " , "Thousand " , "Million " , "Billion "
};
//Number stuff ho!
public static void main( String[] args )
{
String origin = ( args[0] );
int original = Integer.parseInt( origin );
int orlength = origin.length();
int remaindr = ( orlength % 3 );
int legroups;
if ( remaindr != 0 )
{
legroups = ( orlength / 3 + 1 );
}
else
{
legroups = ( orlength / 3 );
}
//Groups AAAARRR here matey!
int groupone = ( original % 1000 );
int grouptwo = ( ( ( original % 1000000 ) - groupone ) / 1000 );
int groupthr = ( ( ( original % 1000000000 ) - grouptwo ) / 1000000 );
//[Pirate themed comment on this being a loop]
boolean finished = false;
int takestep = 0;
while ( finished == false )
{
takestep ++;
int numinact;
if ( takestep == 1 )
{
numinact = groupthr;
}
else if ( takestep == 2 )
{
if ( groupthr != 0 )
{
System.out.print( sections[ 3 ] );
}
numinact = grouptwo;
}
else
{
if ( grouptwo != 0 )
{
System.out.print( sections[ 2 ] );
}
numinact = groupone;
finished = true;
}
if ( numinact > 99 )
{
int hundreds = ( ( numinact - ( numinact % 100 ) ) / 100 );
System.out.print( first [ hundreds ] + sections [ 1 ] );
numinact = ( numinact % 100 );
}
if ( numinact <= 19 )
{
System.out.print( first [ numinact ] );
}
else if ( numinact <= 29 )
{
int digitact = ( numinact - 20 );
System.out.print( second[ 2 ] + first[ digitact ] );
}
else if ( numinact <= 39 )
{
int digitact = ( numinact - 30 );
System.out.print( second[ 3 ] + first[ digitact ] );
}
else if ( numinact <= 49 )
{
int digitact = ( numinact - 40 );
System.out.print( second[ 4 ] + first[ digitact ] );
}
else if ( numinact <= 59 )
{
int digitact = ( numinact - 50 );
System.out.print( second[ 5 ] + first[ digitact ] );
}
else if ( numinact <= 69 )
{
int digitact = ( numinact - 60 );
System.out.print( second[ 6 ] + first[ digitact ] );
}
else if ( numinact <= 79 )
{
int digitact = ( numinact - 70 );
System.out.print( second[ 7 ] + first[ digitact ] );
}
else if ( numinact <= 89 )
{
int digitact = ( numinact - 80 );
System.out.print( second[ 8 ] + first[ digitact ] );
}
else if ( numinact <= 99 )
{
int digitact = ( numinact - 90 );
System.out.print( second[ 9 ] + first[ digitact ] );
}
}
//Yarrr! Debug be what this is!
//System.out.println( " original is " + original + ", orlength is " +
// orlength + ", remaindr is " + remaindr + ", legroups is " +
// legroups + ", groupone is " + groupone + ", grouptwo is " +
// grouptwo + ", groupthr is " + groupthr );
}
}
And this is the C++ re-write that does not work:
//C++ port of the Say.java program.
//I hope to extend to longer numbers in the future.
#include <iostream>
#include <string>
using namespace std;
static string digit [20] =
{
"" , "One " , "Two " , "Three ", "Four ", "Five " , "Six " , "Seven " ,
"Eight " , "Nine " , "Ten " , "Eleven " , "Twelve " , "Thirteen " ,
"Fourteen " , "Fifteen " , "Sixteen " , "Seventeen " , "Eighteen " ,
"Nineteen "
};
int main()
{
int original; //declare int
cout << "Enter your number: "; //Requests user input
cin >> original; //Recieves user input assigns value to previous variable
//Groups of 3 digits
int groupone = ( original % 1000 );
int grouptwo = ( ( original / 1000 ) % 1000);
int groupthr = ( original / 1000000 );
//Intense loop, almost direct from java version.
bool finished = false;
int takestep = 0;
while ( finished != true );
{
takestep ++;
int numinact;
if ( takestep == 1 )
{
numinact = groupthr;
}
else if ( takestep == 2 )
{
if ( groupthr != 0 )
{
cout << "Million ";
}
numinact = grouptwo;
}
else
{
if ( grouptwo != 0 )
{
cout << "Thousand ";
}
numinact = groupone;
finished = true;
}
if ( numinact > 99 )
{
int hundreds = ( ( numinact - (numinact % 100 ) ) / 100 );
cout << digit[ hundreds ] << "Hundred ";
numinact = ( numinact % 100 );
}
if ( numinact <= 19 )
{
cout << digit[ numinact ];
}
else if ( numinact <= 29 )
{
int digitact = ( numinact - 20 );
cout << "twenty " << digit[ digitact ];
}
else if ( numinact <= 39 )
{
int digitact = ( numinact - 30 );
cout << "thirty " << digit[ digitact ];
}
else if ( numinact <= 49 )
{
int digitact = ( numinact - 40 );
cout << "fourty " << digit[ digitact ];
}
else if ( numinact <= 59 )
{
int digitact = ( numinact - 50 );
cout << "fifty " << digit[ digitact ];
}
else if ( numinact <= 69 )
{
int digitact = ( numinact - 60 );
cout << "sixty " << digit[ digitact ];
}
else if ( numinact <= 79 )
{
int digitact = ( numinact - 70 );
cout << "seventy " << digit[ digitact ];
}
else if ( numinact <= 89 )
{
int digitact = ( numinact - 80 );
cout << "eighty " << digit[ digitact ];
}
else if ( numinact <= 99 )
{
int digitact = ( numinact - 90 );
cout << "ninety " << digit[ digitact ];
}
}
return 0;
}
What must I change to get it to run like the java program?
This does not do what you think it does:
bool finished = false;
while ( finished != true );
{
// blah blah blah
finished = true;
}
The semicolon at the end of that while line makes it an infinite loop followed by a block which you never reach (because of that infinite loop).
Remove the semicolon and you will get:
pax$ ./testprog
Enter your number: 1234
One Thousand Two Hundred thirty Four
Related
I am trying to convert a small code of Matlab in c++.
In matlab normalization of random number can be done easily as below:
val = x / norm(x)
where x contains random generated real and img part between 0 and 255 as below:
70.0000000000000 + 112.000000000000i
11.0000000000000 + 97.0000000000000i
24.0000000000000 + 195.000000000000i
210.000000000000 + 203.000000000000i
177.000000000000 + 47.0000000000000i
81.0000000000000 + 125.000000000000i
243.000000000000 + 114.000000000000i
8.00000000000000 + 165.000000000000i
After the normalization, the values in val are as below:
0.126554761381164 + 0.202487618209862i
0.0198871767884686 + 0.175368740771041i
0.0433902039021132 + 0.352545406704670i
0.379664284143491 + 0.367008808005375i
0.320002753778085 + 0.0849724826416384i
0.146441938169632 + 0.225990645323507i
0.439325814508897 + 0.206103468535038i
0.0144634013007044 + 0.298307651827029i
I really donot know how to do the similar work in c++.
I thought of doing something like below but soon got stuck.
int random_real_number;
int random_img_number;
vector<int > real_number;
vector<int> img_number;
int data_size_val= 8;
srand (time(NULL)); // Initialize random seed
for(int i=0;i< data_size_val;i++){
random_real_number = rand() % 255 + 0;
std::cout << random_real_number << std::endl;
random_img_number= rand() % 255 + 0;
std::cout << random_img_number << std::endl;
real_number.push_back(random_real_number);
img_number.push_back(random_img_number);
}
It would be great help if someone can help me in it.
Thanks in advance.
The function std::norm() computes something called the field norm, which is the sum of the squares of real and imag. You get the square root of that with std::abs(). So in the same vein as the example on the C++ website, you can do:
#include <vector>
#include <cassert>
#include <complex>
#include <iostream>
#include <iomanip>
int main() {
std::vector < std::complex < double > >
zarray { { 70, 112 }, { 11, 97 }, { 24, 195 }, { 210, 203 },
{ 177, 47 }, { 81, 125 }, { 243, 114 }, { 8, 165 } };
for ( auto z: zarray ) {
assert ( std::norm ( z ) == ( z.real() * z.real() + z.imag() * z.imag() ) );
assert ( std::norm ( z ) == ( z * std::conj ( z ) ) );
// assert ( std::norm ( z ) == ( std::abs ( z ) * std::abs ( z ) ) );
std::cout << "std::abs ( " << std::setw(9) << z << " ) = "
<< std::setw(7) << std::abs ( z )
<< ", z/abs = " << std::setw(19) << z / std::abs ( z ) << '\n';
}
}
which should return
std::abs ( (70,112) ) = 132.076, z/abs = (0.529999,0.847998)
std::abs ( (11,97) ) = 97.6217, z/abs = (0.11268,0.993631)
std::abs ( (24,195) ) = 196.471, z/abs = (0.122155,0.992511)
std::abs ( (210,203) ) = 292.077, z/abs = (0.718988,0.695022)
std::abs ( (177,47) ) = 183.134, z/abs = (0.966506,0.256643)
std::abs ( (81,125) ) = 148.95, z/abs = (0.543808,0.83921)
std::abs ( (243,114) ) = 268.412, z/abs = (0.905325,0.42472)
std::abs ( (8,165) ) = 165.194, z/abs = (0.048428,0.998827)
The first complex number in your example is divided by 553.12, but I don't really see how that would be the L2-norm of 70+112i.
For the C++ experts: compared to the example I had to comment out the last assert because it fails on some of the inputs, I'm not sure why that is.
I wrote a simple algorithm to display the nth prime. Simply put, it uses a vector of found primes to check if the next number is prime as well; if it is, it pushes it into the vector and repeats until the nth prime is found.
Unfortunately, I am getting a segmentation fault in the for loop nested in the while loop and I have no idea why. More specifically, the error occurs in the header of the for loop; I added a cerr << "Check " << z++ << endl; to the body of the for loop (and one before it altogether) to see where it occurred so I believe the error is related to the iterators.
The program is very small and I don't mind sharing it (if you have a use for it have at it) so here's the whole thing:
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <vector>
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
int main( int argc, char* argv[] )
{
if( argc != 2 )
{
cerr << "USAGE: nthPrime n" << endl;
return 1;
}
vector< unsigned > primes;
vector< unsigned >::iterator it;
bool isPrime;
char *sffx = ( char ) 0;
unsigned n = atoi( argv[ 1 ] ),
x = 3,
max;
primes.push_back( 2 );
while( primes.size() != n )
{
isPrime = true;
max = ( unsigned )sqrt( x );
for( it = primes.begin(); *it <= max; ++it )
if( !( x % *it ) ) isPrime = false;
if( isPrime ) primes.push_back( x );
x += 2;
}
if( n == 1 ) strcpy( sffx, "st" );
else if( n == 2 ) strcpy( sffx, "nd" );
else if( n == 3 ) strcpy( sffx, "rd" );
else strcpy( sffx, "th" );
cout << "The " << n << sffx << " prime is " << primes.back() << endl;
return 0;
}
Here's the makefile too for convienience:
CCFLAGS = -Wall -std=c++11
nthPrime: nthPrime.o
g++ $(CCFLAGS) -o nthPrime nthPrime.o
nthPrime.o: nthPrime.cpp
g++ $(CCFLAGS) -c nthPrime.cpp
clean:
-rm *.o nthPrime
I have neglected to add any comments as I just wrote it an hour ago so please let me know if you would like me to.
Thanks in advance.
P.S. I have tried adding && it != primes.end() to the for loop but it shouldn't be required due to the properties of the algorithm and it didn't help anyway.
Some issues I can see:
1) using argv without checking
unsigned n = atoi( argv[ 1 ] ),
x = 3,
max;
2) This:
char *sffx = ( char ) 0;
Does not allocate space for this:
if( n == 1 ) strcpy( sffx, "st" );
else if( n == 2 ) strcpy( sffx, "nd" );
else if( n == 3 ) strcpy( sffx, "rd" );
else strcpy( sffx, "th" );
Ok thank you everyone for getting back to me so quickly! I thought I'd be waiting all day! The issue turned out to be the line char *sffx = ( char ) 0;. Changing it to char *sffx = new char[ 3 ]; fixed everything.
For anyone who may end up having a similar issue or just wants the program for whatever reason, here it is:
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <vector>
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
int main( int argc, char* argv[] )
{
vector< unsigned > primes;
vector< unsigned >::iterator it;
bool isPrime;
char *sffx = new char[ 3 ];
unsigned n = atoi( argv[ 1 ] ),
x = 3,
max;
if( argc != 2 || n < 1)
{
cerr << "USAGE: nthPrime n>0" << endl;
return 1;
}
primes.push_back( 2 );
while( primes.size() < n )
{
isPrime = true;
max = ( unsigned )sqrt( x );
for( it = primes.begin(); *it <= max; ++it )
if( !( x % *it ) ) isPrime = false;
if( isPrime ) primes.push_back( x );
x += 2;
}
if( n % 10 == 1 && n % 100 != 11 ) strcpy( sffx, "st" );
else if( n % 10 == 2 && n % 100 != 12 ) strcpy( sffx, "nd" );
else if( n % 10 == 3 && n % 100 != 13 ) strcpy( sffx, "rd" );
else strcpy( sffx, "th" );
cout << "The " << n << sffx << " prime is " << primes.back() << endl;
return 0;
}
Enjoy and thank you all again!
P.S. the 86626th prime is a cool one I just ran into randomly to test the program at a high value; check it out!
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 8 years ago.
Improve this question
Could someone answer the below C++ interview question:
Given string: "song singing in hindi"
find repeated strings like as below :
single characters repetition:
Count of "s" = 2 Count of "o" = 0 Count of "n" = 5 Count of "g" = 3
..... etc
two character repetition
Count of "so" = 0 Count of "on" = 0 Count of "ng" = 3 Count of "in" = 4..... etc
Three character repetition
Count of "son" = 0 ....Count of "ing" = 1.... etc
Four character repetition
Count of "song" = 0 .....etc
Rs
Or even a recursive function would do. To remove the 'patterns' with a white space you can follow Vlad's approach with the string::find function.
#include <iostream>
#include <string>
#include <map>
class FRQ {
void Func(std::map<std::string, size_t> &frequencyTable, const std::string &m_str, const int stepping = 1) {
if (stepping == m_str.size()) {
frequencyTable[m_str]++;
return;
}
for (std::string::size_type i = 0, iMAX = m_str.size(); i < iMAX; ++i) {
frequencyTable[m_str.substr(i, stepping)]++;
}
Func(frequencyTable, m_str, stepping + 1);
}
public:
std::map<std::string, size_t> *operator()(const std::string &str) {
std::map<std::string, size_t> *fTable = new std::map<std::string, size_t>();
Func(*fTable, str);
return fTable;
}
};
int main(void) {
using namespace std;
string s = "HiYo HiYo";
FRQ frq;
map<string, size_t> *frequenceTable = frq(s);
cout << "Patterns: " << frequenceTable->size() << endl;
for (const auto& ptr : *frequenceTable)
cout << "[ '" << ptr.first << "'::" << ptr.second << " ]" << endl;
delete frequenceTable;
return 0;
}
Here is a straightforward approach
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string s = "song singing in hindi";
for ( std::string::size_type i = 1; i <= s.size(); i++ )
{
std::map<std::string, size_t> m;
for ( std::string::size_type j = 0; j < s.size() - i + 1; j++ )
{
m[std::string( s, j, i )]++;
}
for ( const auto &p : m )
{
std::cout << "( \"" << p.first << "\", " << p.second << " ) ";
}
std::cout << std::endl;
}
return 0;
}
If you want to exclude patters with an embedded blank you can rewrite the program the following way
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string s = "song singing in hindi";
for ( std::string::size_type i = 1; i <= s.size(); i++ )
{
std::map<std::string, size_t> m;
for ( std::string::size_type j = 0; j < s.size() - i + 1; j++ )
{
std::string t( s, j, i );
if ( t.find( ' ' ) == std::string::npos )
{
m[t]++;
}
}
if ( !m.empty() )
{
for ( const auto &p : m )
{
std::cout << "( \"" << p.first << "\", " << p.second << " ) ";
}
std::cout << std::endl;
}
}
return 0;
}
The output is
( "d", 1 ) ( "g", 3 ) ( "h", 1 ) ( "i", 5 ) ( "n", 5 ) ( "o", 1 ) ( "s", 2 )
( "di", 1 ) ( "gi", 1 ) ( "hi", 1 ) ( "in", 4 ) ( "nd", 1 ) ( "ng", 3 ) ( "on", 1 ) ( "si", 1 ) ( "so", 1 )
( "gin", 1 ) ( "hin", 1 ) ( "ind", 1 ) ( "ing", 2 ) ( "ndi", 1 ) ( "ngi", 1 ) ( "ong", 1 ) ( "sin", 1 ) ( "son", 1 )
( "ging", 1 ) ( "hind", 1 ) ( "indi", 1 ) ( "ingi", 1 ) ( "ngin", 1 ) ( "sing", 1 ) ( "song", 1 )
( "hindi", 1 ) ( "ingin", 1 ) ( "nging", 1 ) ( "singi", 1 )
( "inging", 1 ) ( "singin", 1 )
( "singing", 1 )
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > number;
bool numbersAreCorrect = false;
int input;
while( cin >> input )
number.push_back( input );
vector< int > unique_number( number.size(), 0 );
vector< int > repeated( number.size(), 1 );
for( int i = 0; i < number.size(); i++ )
{
for( int j = i + 1; j < number.size() + 1; j++ )
{
if( number[ i ] != 0 && number[ i ] == number[ j ] )
{
repeated[ i ]++;
unique_number[ i ] = number[ i ];
}
else
unique_number[ i ] = number[ i ];
if( j == number.size() )
{
for( int z = 0; z < number.size(); z++ )
{
if( number[ z ] == unique_number[ i ] )
number[ z ] = 0;
}
}
}
}
for( int i = 0; i < number.size(); i++ )
{
if( ( unique_number[ i ] != 0 && repeated[ i ] == 1 ) || ( unique_number[ i ] != 0 && repeated[ i ] % 2 != 0 ) )
{
numbersAreCorrect = false;
cout << unique_number[ i ] << endl;
break;
}
else if( repeated[ i ] == 1 )
numbersAreCorrect = true;
else if( repeated[ i ] % 2 != 0 )
{
numbersAreCorrect = false;
cout << repeated[ i ] << endl;
break;
}
else if( repeated[ i ] % 2 == 0 )
numbersAreCorrect = true;
}
if( numbersAreCorrect == true )
cout << "0" << endl;
return 0;
}
This program gets positive integers from user, checks if an integer is repeated 2k( even) times or 2k+1(odd) times. if latter is true, it prints the integer , else it prints 0; I used 20000 inputs and it takes more than 10 seconds to evaluate.. I need to know how to make it process faster.
for example this input results in "0" : 1 2 2 1
and this results in "3" : 1 2 2 1 3
How about you first sort the thing.
Then you only need to do a single for loop instead of two because to find all the repetitions you just count consecutive occurrences.
Failing that use a set or map. Again you'll drop to O(NlogN) instead of O(N^2).
I am looking to convert existing code in C to perform the following: I am attempting to write a hex dump program that prints out address: values printable characters.
Currently, the code for values is printing in the following format:
0003540: 05 04 06 75 6e 73 69 67 6e 65 64 20 63 68 61 72 ...unsigned char
Desired hex output:
0003540: 0504 0675 6e73 6967 6e65 6420 6368 6172 ...unsigned char
Current code printing in pairs:
addr = 0;
while ( ( cnt = ( long )
fread ( buf, sizeof ( unsigned char ), 16, filein ) ) > 0 ) {
b = buf;
/* Print the address in hexadecimal. */
fprintf ( fileout, "%07lx ", addr );
addr = addr + 16;
/* Print 16 data items, in pairs, in hexadecimal. */
cnt2 = 0;
for ( m = 0; m < 16; m++ ) {
cnt2 = cnt2 + 1;
if ( cnt2 <= cnt ) {
fprintf ( fileout, "%02x", *b++ );
}
else {
fprintf ( fileout, " " );
}
fprintf ( fileout, " " );
}
/* Print the printable characters, or a period if unprintable. */
fprintf ( fileout, " " );
cnt2 = 0;
for ( n = 0; n < 16; n++ ) {
cnt2 = cnt2 + 1;
if ( cnt2 <= cnt ) {
if ( ( buf[n] < 32 ) || ( buf[n] > 126 ) ) {
fprintf ( fileout, "%c", '.' );
}
else {
fprintf ( fileout, "%c", buf[n] );
}
}
}
fprintf( fileout, "\n" );
}
How can I alter this code to achieve the AB12 CD34 format?
Thanks!
Use the modulo (remainder) operator % to test if m is divisible by 2. Only write the space when it is:
for ( m = 0; m < 16; m++ ) {
if ( m > 0 && m % 2 == 0 ) {
fprintf ( fileout, " " );
}
fprintf ( fileout, "%02x", *b++ );
}
Edit 3:
for ( m = 0; m < 16; m++ ) {
if ( m > 0 && m % 2 == 0 ) {
fprintf ( fileout, " " ); // space between every second byte
}
if ( m < cnt ) {
fprintf ( fileout, "%02x", *b++ );
} else {
fprintf ( fileout, " " ); // blank if run out of bytes on this line
}
}
I think this can be simplified quite a bit. For example, I'd consider starting with something like this:
#include <stdio.h>
#include <ctype.h>
int main(){
char buffer[17];
size_t bytes;
int i;
while (0 < (bytes = fread(buffer, 1, 16, stdin))) {
for (i = 0; i < bytes / 2; i++) // print out bytes, 2 at a time
printf("%02x%02x ", buffer[i * 2], buffer[i * 2 + 1]);
if (i * 2 < bytes) // take care of (possible) odd byte
printf("%02x ", buffer[i * 2]);
for (; i < 8; i++) // right pad hex bytes
printf(" ");
for (i = 0; i < bytes; i++) // change unprintable to '.'
if (!isprint(buffer[i]))
buffer[i] = '.';
buffer[i] = '\0'; // terminate string
printf("\t%s\n", buffer); // print out characters
}
return 0;
}