Question:
C programming language help?
Alex
2012-09-12 01:43:31 UTC
Hi, im relatively experienced in python programming but am new to C

I have this code which i need some help with:
printf("Please input the total weight in pounds of locamotive (W): ");
scanf("%d", &W);

I would like to add an if condition
Basically, if the input contains a "," comma I would like the program to remove the comma

Example:
if someone inputs "200,000" i want the program to remove the comma and store the variable W without the comma as "200000"

How do i do this?

Thanks
Seven answers:
AnalProgrammer
2012-09-12 02:04:04 UTC
The function you have

scanf("%d", &W);

is only reading integers. That is what the %d does. If you want to get anything else the you need to change the data type that you are reading. Perhaps a string or a char array should be input. Then you have the chance to edit the data as you require. Also because you have a string you will have to do full validation.



Have fun.
Δημήτρης
2012-09-13 03:39:23 UTC
You could read the entire input in a loop as a character string

char ch[10];

int i = -1;

e.g. do{

i++;

scanf("%c", &ch[i]);

}while(ch!='\n');

then clear the comma from the character string and then call atoi() function that converts an ascII to an integer value (returns int).

Come on! Do some coding, think and search! Don't ask everyone else to do what you are supposed to do! You will learn nothing like this!
?
2016-07-28 01:25:31 UTC
Just google c++ and there are a number of tutorial web sites. As far as studying the language is worried, It takes a long time and that you could continually gain knowledge of new things. Additionally dont expect it to be easy, but if different languages its absolutely a massive plus
Ross
2012-09-12 02:07:22 UTC
Just do a web search, you'll find several examples. This is a popular problem.
Anas Imtiaz
2012-09-12 03:42:44 UTC
Click the link to find the code + sample run: http://ideone.com/kLkwo
aj1490
2012-09-13 04:14:15 UTC
#include

#include

#include



int main()

{

char s[20],n[20];

long int Num = 0;

int i,j;



scanf("%s",s);



for(i=strlen(s)-1,j=0; i>=0; i--)

{

if(s[i] != ',')

n[j++] = s[i];

}



for(i=0; i
Num += ((n[i]-'0') * pow(10,i));



printf("No is : %ld",Num);

return 0;

}
Anil
2012-09-12 02:32:47 UTC
just do search at google or http://www.cprogramming.com/ this site i hope you will find out your answer


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...