Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi experts, I need to preserve any leading zeroes in the input so I took the digits in as char’s and then convert them back
to integers using the ctoi function (see below).


C++
#include<stdio.h>
#define ctoi(a)  a-'0'
int main()
{
    int n;
    char ch;
    scanf("%c",&n);
    ch=ctoi(n);

    printf("%c",n);

}



But the code didn't work. I'm not sure where is the problem.
Input:

001
0123
78
000123

Expected Output:
1
123
78
123


But I got:
0
0
7
0


What I have tried:

I tried the input (may have leading zeros) first convert into char and then again to integers.....
Posted
Updated 10-Apr-16 8:31am
v5
Comments
Patrice T 10-Apr-16 13:37pm    
Define "code didn't work"
Member 12378355we 10-Apr-16 13:56pm    
How? It should work.....
Patrice T 10-Apr-16 14:02pm    
Tell what it do and what is the problem.
if wrong result, give and example with what it do and what you want.
Member 12378355we 10-Apr-16 14:09pm    
Updated question. And included input and desired output
Patrice T 10-Apr-16 14:16pm    
good

1 solution

Obviously, your own code is like a blackbox to you. It don't do what you expect, and you don't understand why.
What follow is not directly a solution to your problem, but a key that will help you to understand by yourself what is wrong.
The debugger is your friend. It will show you what your code is really doing.
Follow the execution, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Debugger - Wikipedia, the free encyclopedia[^]

Your program is a mess, here is what your program is really doing
C++
#include<stdio.h>
#define ctoi(a)  a-'0'
int main()
{
    int n;
    char ch;
    scanf("%c",&n);
    ch=ctoi(n);
     printf("%c",n);
}

Only the debugger can tell you what really append in this code.
You really need to follow tutorials and examples programs.

By the way, it look like HomeWork. If you fail to solve the problem, it is a useful information for your teacher.
And showing your own work that fail is better than showing someone else work that you don't understand.
 
Share this answer
 
v4
Comments
Member 12378355we 10-Apr-16 14:35pm    
Your code still output like my previous code...
Patrice T 10-Apr-16 14:40pm    
Yes I show you what your code is really doing!
Patrice T 10-Apr-16 14:46pm    
You have a lot of work to learn C properly and giving you a full blowup solution is not a good service for your learning

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900