views:

195

answers:

4

Hello there, Basically i got this for loop and i want the number inputed (eg. 123) to be printed out in reverse, so "321". so far it works fine and prints out the correct order when the for loop is

for(i = 0; i<len ; i++)

but i get an error when i try to print it in reverse?. Whats going wrong?

#include <stdio.h>
#include <string.h>
void cnvrter(char *number);

int main(){
    char number[80];
    printf("enter a number ");
    gets(number);
    cnvrter(number);

    return 0;
}

void cnvrter(char *number){
    char tmp[80];
    int i = 0,len = 0;
    int cnvrtd_digit = 0;
    len = strlen(number);
    printf("\nsize of input %d\n",len);
    for(i = len; i>len ; i--){
        if ( ( number[i] >= '0' ) && ( number[i]<='9' ) ){
            tmp[0] = number[i];
            sscanf(tmp,"%d",&cnvrtd_digit);

        }
        printf("%d\n",cnvrtd_digit);
    }
}
A: 

You never advance the index on tmp, and you never null-terminate it.

Ignacio Vazquez-Abrams
+4  A: 

Look at your for loop again:

for(i = len; i>len ; i--){

You're doing i=len, and then testing for i>len -- unless something goes seriously wrong in the assignment, that's never going to be true...

By the way, though it's not related, you shouldn't be using gets, even in a program like this that you never intend to put to serious use.

Jerry Coffin
hmmm when i use for(i = len; i>=0 ; i--) i get 0321 printed out. why does this 0 appeare?
sil3nt
In C and C++, array indices start at 0, so for a string with a length of 3, the largest valid index is 2.
Jerry Coffin
ahh cheers! thank you very much
sil3nt
You should use i=len-1, not i=len.
Spidey
A: 

I think that`s wrong:

for(i = len; i>len ; i--){

Maybe like:

for(i = len-1; i>=0; i--){
gmunkhbaatarmn
Thanks for your attempt. Please try again.
Martin York
+1  A: 

You don't need an explicit for-loop to reverse a string in C++. You could use std::reverse() or str.rbegin(), str.rend().

// -*- coding: utf-8 -*-
// $ g++ *.cc && (echo 'abc1d23e->١<-_ f999fff' | ./a.out)
#include <algorithm>  // remove_copy_if
#include <functional> // not1
#include <iostream>
#include <iterator>   // ostream_iterator
#include <string>

int main() {
  using namespace std;

  cout << "enter a number " << flush;               // print prompt
  string str; cin >> str;                           // read until first space
  cout << "\nsize of input " << str.size() << endl;

  remove_copy_if(
      str.rbegin(), str.rend(),                     // traverse in reverse order
      ostream_iterator<string::value_type>(cout, "\n"), // copy to stdout
                                                        // separated by newline
      not1(ptr_fun((int (*)(int))isdigit)));        // remove non-digits
}

Run it:

$ g++ *.cc && (echo 'abc1d23e->١<-_ f999fff' | ./a.out)
enter a number 
size of input 15
3
2
1
J.F. Sebastian