Write a program that reads a series of phone numbers from a file and displays th
ID: 645930 • Letter: W
Question
Write a program that reads a series of phone numbers from a file and displays them in a standard format. Each
line of the file will contain a single phone number, but the numbers may be in a variety of formats. You may
assume that each line contains 10 digits, possibly mixed with other characters (which should be ignored). For
example, suppose that the file contains the following lines:
404.817.6900
(215) 686-1776
312-746-6000
877 275 5273 FREE
6173434200
The output of the program should have the following appearance:
(404) 817-6900
(215) 686-1776
(312) 746-6000
(877) 275-5273 FREE
(617) 343-4200
post progrm or .c file
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("C: cc umbers.txt", "r");
while ( getline(fp, str)) { //to read line from file
printf("("); //to print ( at first
int count=0,i;
for( i=0;;i++){
if(str[i]-'0' >=0 && str[i]-'0'<=9){ //to print next 3 digits
count++;
printf("%c",str[i]);
}
if(count==3) break; //after printing 3 digits leave the for loop
}
printf(") "); //to print ) after that
for( ;;i++){
if(str[i]-'0' >=0 && str[i]-'0'<=9){ //to print next 3 digits
count++;
printf("%c",str[i]);
}
if(count==6) break; //after printing next 3 digits leave the for loop
}
printf("-"); //to print - after that
for( ;i<str.length();i++){
if(str[i]-'0' >=0 && str[i]-'0'<=9){ //to print next 4 digits
count++;
printf("%c",str[i]);
}
if (count==10) break; //when count is equal to 10, exit the for loop
}
printf(" "); //go to new line
} //go to the begining of while to process next line
return 0;
}
Explanation / Answer
#include <stdio.h>
int main()
{
FILE *fp;
char c;
int count=0,flag0=0,flag1=0,flag2=0;
fp = fopen("numbers.txt", "r");
while((c = fgetc(fp)) != EOF)
{
if(count==0 && flag0==0)
{
printf("(");
flag0=1;
}
if(count==3 && flag1==0)
{
printf(")");
flag1=1;
}
if(count==6 && flag2==0)
{
printf("-");
flag2=1;
}
if(c=='0' || c=='1' || c=='2' ||c=='3' ||c=='4' ||c=='5' ||c=='6' ||c=='7' ||c=='8' ||c=='9')
{
putchar(c);
count++;
}
if(count==10)
{
count=0;flag0=0;flag1=0;flag2=0;
printf(" ");
}
}
fclose(fp);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.