请忘记scanf 的存在。您遇到的问题,虽然主要是由于您可以理解的缺乏经验造成的,但即使您有经验,也会继续困扰您 - 直到您停下来。
原因如下:
scanf 将读取输入,并将结果放入您提供的char 缓冲区。但是,它将不检查以确保有足够的空间。如果它需要的空间比您提供的更多,它将覆盖其他内存位置 - 通常会带来灾难性的后果。
更安全的方法使用fgets - 这是一个与scanf 大致相同的功能,但它只会读取与您创建空间一样多的字符(或:如您说 你为它创造了空间)。
其他观察:sizeof 只能评估大小编译时已知:原始类型(int、double 等)占用的字节数或固定数组的大小(如诠释我[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;
}
我希望这会有所帮助。
更新您提出了合理的后续问题:“我怎么知道字符串太长”。
请参阅此代码 sn-p 以获得灵感:
#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 个字符的空间时,最后一个字符(在位置 N-1)必须是 '\0',并且由于 fgets 包含 '\n',因此您可以输入的最大字符串实际上是 N-2字符长。