我目前正在学习C,因此我想编写一个程序,要求用户输入字符串并输出输入的字符数,代码可以很好地编译,当我只输入1个字符时,它就可以了,但是当我输入2个或更多字符,无论我输入多少个字符,总会说只有一个字符,此后就会崩溃。这是我的代码,我无法弄清楚出了什么问题。
int main(void)
{
int siz;
char i[] = "";
printf("Enter a string.\n");
scanf("%s", i);
siz = sizeof(i)/sizeof(char);
printf("%d", siz);
getch();
return 0;
}
我目前正在学习编程,因此,如果有一种方法可以使用相同的scanf()函数,我将不胜感激,因为我还没有学会如何使用任何其他函数,并且可能不会理解它是如何工作的。
请,忘记scanf
存在。虽然您遇到的问题主要是由您可以理解的缺乏经验造成的,但是即使您有经验,问题也会继续对您造成伤害-直到您停止为止。
原因如下:
scanf
将读取输入,并将结果放入char
您提供的缓冲区中。但是,它不会检查以确保有足够的空间。如果需要的空间超过了您提供的空间,它将覆盖其他内存位置-通常会造成灾难性的后果。
一种更安全的方法是使用fgets
-此函数的功能与大致相同scanf
,但是只会读取与您为其创建空格(或:正如您所说的为空格)一样多的字符。
其他观察:sizeof
只能评估编译时已知的大小:原始类型(int,double等)占用的字节数或固定数组的大小(如int i [100];)。它不能用于确定程序期间的大小(如果“大小”是变化的东西)。
您的程序如下所示:
#include <stdio.h>
#include <string.h>
#define BUFLEN 100 // your buffer length
int main(void) // <<< for correctness, include 'void'
{
int siz;
char i[BUFLEN]; // <<< now you have space for a 99 character string plus the '\0'
printf("Enter a string.\n");
fgets(i, BUFLEN, stdin); // read the input, copy the first BUFLEN characters to i
siz = sizeof(i)/sizeof(char); // it turns out that this will give you the answer BUFLEN
// probably not what you wanted. 'sizeof' gives size of array in
// this case, not size of string
// also not
siz = strlen(i) - 1; // strlen is a function that is declared in string.h
// it produces the string length
// subtract 1 if you don't want to count \n
printf("The string length is %d\n", siz); // don't just print the number, say what it is
// and end with a newline: \n
printf("hit <return> to exit program\n"); // tell user what to do next!
getc(stdin);
return 0;
}
我希望这有帮助。
更新时您提出了合理的后续问题:“我怎么知道字符串太长”。
请参见以下代码段以获取灵感:
#include <stdio.h>
#include <string.h>
#define N 50
int main(void) {
char a[N];
char *b;
printf("enter a string:\n");
b = fgets(a, N, stdin);
if(b == NULL) {
printf("an error occurred reading input!\n"); // can't think how this would happen...
return 0;
}
if (strlen(a) == N-1 && a[N-2] != '\n') { // used all space, didn't get to end of line
printf("string is too long!\n");
}
else {
printf("The string is %s which is %d characters long\n", a, strlen(a)-1); // all went according to plan
}
}
请记住,当您有N个字符的空间时,最后一个字符(在location处N-1
)必须为a,'\0'
并且由于fgets
包括了'\n'
您可以输入的最大字符串,因此实际上是N-2
字符长。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句