gpt4 book ai didi

C程序在输入字符串后没有结束?

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:15 24 4
gpt4 key购买 nike

我正在完成一个编程练习,当我的程序运行时,它永远不会执行超过输入行的任何内容,也永远不会终止。没有错误或警告出现,所以我不确定出了什么问题。任何帮助都会很棒。

这是作业:编写一个函数,要求用户输入一个电话号码,该电话号码是一个字符串,其中包含一个三位数的区号,后跟一个七位数的号码。任何其他字符将被忽略,仅将考虑前 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;
}

关于C程序在输入字符串后没有结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com