[英]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.