我的C程序假设接收一个全名,以逗号分隔。示例输出如下:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string:
Washington,DC
First word: Washington
Second word: DC
Enter input string:
q*
但是,使用我当前的代码,Jill, Allen
可以按预期工作,但是其他两个名称不能正常工作,因为缺少第一个字母。我认为这是由于输入格式引起的。每个名称都用新行分隔,因此机器不会读取终止行,因此会忽略第一个字母。这是我的代码现在输出时的样子:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: olden
Second word: ,
Enter input string:
Washington,DC
First word: ashington
Second word: ,
如您所见,第一个单词的第一个字母丢失了,然后弄乱了第二个单词。任何建议,将不胜感激谢谢。我的代码:
#include<stdio.h>
#include <string.h>
int main(void) {
char name[100];
char firstName[100];
char lastName[100];
char comma = ',';
char quit;
int i;
while(quit != 'q')
{
printf("Enter input string:\n");
fgets(name, 100, stdin);
scanf("%c", &quit);
if(!(strchr(name, comma)))
{
printf("Error: No comma in string.\n\n");
}
if((strchr(name, comma)))
{
sscanf(name, "%s%s", firstName, lastName);
for(i = 0; i < strlen(name); i++)
{
if(firstName[i] == ',')
{
firstName[i] = '\0';
}
}
printf("First word: %.10s\n", firstName);
printf("Second word: %.10s\n\n", lastName);
}
}
printf("Enter input string:\n");
return 0;
}
由于要在用户键入“ q”时停止,因此应检查读取的内容fgets()
,如果该值等于字符串“ q”,则中断循环。
所以现在,您将不会读入name
,而是读入,line
因为您正在阅读的内容可以有效地是名称或退出命令。
此外,这意味着您可以使用“无限期”运行(停止条件为1)直到用户输入“ q”的do-while循环,而不是while循环。
此外,您不需要结尾的换行符fgets()
,因此可以将其删除。
正如@weatherVane所评论的那样:sscanf(name, "%s%s", firstName, lastName);
不会停在您检测到的逗号处:每个部分都停在一个空白字符处。
但是,您需要忽略空格字符(如果有的话),因此sscanf()
可以在调用之后不运行for循环,而无需使用该方法,而是使用两个循环,一个循环填充第一个名称,然后另一个循环填充以姓氏命名。
将所有内容放在一起,您将获得:
#include<stdio.h>
#include <string.h>
int main(void)
{
char line[100];
char firstName[100];
char lastName[100];
char comma = ',';
do {
printf("Enter input string:\n");
fgets(line, 100, stdin);
line[strcspn(line, "\n")] = 0;
if(!strcmp(line, "q"))
{
printf("Exiting..\n");
break;
}
if(!(strchr(line, comma)))
{
printf("Error: No comma in string.\n\n");
}
if((strchr(line, comma)))
{
int i = 0, j = 0; // i'' index for line, 'j' index for 'firstName'
while(line[i] != ',')
{
if(line[i] != ' ')
{
firstName[j] = line[i];
j++;
}
i++;
}
i++; // since we had stopped at the comma character
firstName[j] = '\0';
int k = 0; // 'k' index for 'lastName'
while(line[i] != '\0')
{
if(line[i] != ' ')
{
lastName[k] = line[i];
k++;
}
i++;
}
lastName[k] = '\0';
printf("First word: %.10s\n", firstName);
printf("Second word: %.10s\n\n", lastName);
}
} while(1);
return 0;
}
输出:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string:
Washington,DC
First word: Washington
Second word: DC
Enter input string:
q
Exiting..
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句