[英]C Program not ending after inputting string?
我正在完成编程练习,并且在我的程序运行时,它从不执行超出输入行的任何操作,并且永不终止。 没有错误或警告出现,所以我不确定是什么错误。 任何帮助都会很棒。
这是作业:编写一个函数,要求用户输入电话号码作为包含三位数字区号和七位数字的字符串。 其他任何字符都将被忽略,并且仅考虑前10位数字。 假设该字符串最多包含200个字符。 如果用户未提供至少10位数字,则应打印出错误消息。 它应该以(123)456-7890格式报告电话号码。 请注意,用户可以选择任何输入格式,但是程序应保持一致的输出格式。 该函数应称为phone_fmt。 您的可执行文件将称为电话。 函数和main应该分别在文件phone_fmt.c,phone_fmt.h和phone.c中。
这是我的phone.c代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "phone_fmt.h"
int main(){
char numStr[200];
char phoneNum[14];
int i=0;
printf("Enter phone number string up to 200 characters: \n ");
scanf("%s", numStr);
if(strlen(numStr)<10){
printf("Invalid. Entry must be at least 10 characters.\n");
exit(1);
}
while(numStr[i] != '\0' && i<10){
if(numStr[i]>'0' && numStr[i]<'9')
break;
i++;
}
if(i > 10){
printf("Invalid. Not enough digits to complete phone number.\n");
exit(1);
}
phone_fmt(numStr, phoneNum);
printf("Phone number: %s \n", phoneNum);
return 0;
}
phone_fmt.c的代码
#include "phone_fmt.h"
void phone_fmt(char *numStr, char *phoneNum){
int i=0;
int j=0;
int c=0;
while(numStr[i] != '\0' && c < 10){
if(j==0){
phoneNum[j]='(';
j++;
}
else if(j==4){
phoneNum[j]=')';
j++;
}
else if(j==8){
phoneNum[j]='-';
j++;
}
if(numStr[i] >= '0' && numStr[i] <= '9'){
phoneNum[j]=numStr[i];
j++;
}
}
}
phone_fmt.h的代码
#include<stdio.h>
void phone_fmt(char *numStr, char *phoneNum);
任何帮助将不胜感激。
根据您的逻辑,您需要创建一个char或int数组,以将10个电话数字保留为phone_fmt()函数中的第一个参数。 工作的代码如下。
#include <stdio.h>
void phone_fmt(int *digits, char *phoneNum){
sprintf(phoneNum, "(%d%d%d) %d%d%d-%d%d%d%d", digits[0],
digits[1],
digits[2],
digits[3],
digits[4],
digits[5],
digits[6],
digits[7],
digits[8],
digits[9]);
}
int main(){
char output[20];
int digits[10];
char c;
int i = 0, j = 0;
printf("Enter phone number string up to 200 characters: \n ");
while( (c = getchar()) != '\n' && i < 10 ){
if( (c >= '0' && c <= '9') ){
digits[i++] = (int)(c - '0');
}
++j;
}
if( j < 10 || j > 200 ){
printf("Invalid. Entry must be at least 10 characters and less then 200 characters.\n");
return -1;
}
if(i < 10){
printf("Invalid. Not enough digits to complete phone number.\n");
return -1;
}
phone_fmt(digits, output);
printf("Phone number: %s \n", output);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.