【发布时间】:2014-03-21 02:26:02
【问题描述】:
编写一个要求用户输入 3 个字符串的程序。然后程序获取每个字符串并计算数字、小写字母和标点符号的数量。程序编译,但用户输入第一个字符串后,出现分段错误,程序崩溃。 当我运行程序时,结果如下:
输入第一个字符串 :1 输入第二个字符串 :输入第二个 string :2 分段错误
不确定到底发生了什么,但任何帮助都会很棒!谢谢。
#include <stdio.h>
#include <string.h>
int countDigit(char *s);
int countLower(char *s);
int countPunct(char *s);
int main (void)
{
int digit, lower, punct;
char *first;
char *second;
char *third;
char *c;
printf("Enter the first string\n:");
scanf("%99s", first);
printf("Enter the second string\n:");
scanf("%99s", second);
printf("Enter the second string\n:");
scanf("%99s", third);
digit=countDigit(first);
lower=countLower(first);
punct=countPunct(first);
printf("There are %d digits, %d lower case letters and %d punctuation chars in a\n", digit, lower, punct);
digit=countDigit(second);
lower=countLower(second);
punct=countPunct(second);
printf("There are %d digits, %d lower case letters and %d punctuation chars in b\n", digit, lower, punct);
digit=countDigit(third);
lower=countLower(third);
punct=countPunct(third);
printf("There are %d digits, %d lower case letters and %d punctuation chars in c\n", digit, lower, punct);
}
int countDigit(char *s)
{
int count = 0;
char temp;
while(*s !=0)
{
temp = *s;
if (isdigit(temp))
{
count++;
}
s++;
}
return count;
}
int countLower(char *s)
{
int count = 0;
char temp;
while (*s !=0)
{
temp = *s;
if (islower(temp))
{
count++;
}
s++;
}
return count;
}
int countPunct(char *s)
{
int count = 0;
char temp;
while (*s !=0)
{
temp = *s;
if (ispunct(temp))
{
count++;
}
s++;
}
return count;
}
【问题讨论】:
-
只是对未来问题的建议。您应该尽量保留您的问题short but self contained。由于您在输入后得到 Segmentation Fault,因此您可以确定问题出在开头,而其他所有内容都可以忽略。此外,您的问题中没有 c++ 元素,因此不应使用该标签,否则您可能会得到 c++ 答案,如果您实际上正在使用 c,则无法使用。